I am displaying a datepicker using the datepicker fragment. I init my datepicker with my previously selected date.
While loading datepicker with the previous date I am unable to select the current date from datepicker. I face this issue in API Level 21 only. It's working in all API levels expects API 21.
Whenever I remove maxDate() from datepicker, It started working out. But in my case, I need to disable future dates.
I don't understand what is wrong with my code.
Here is my code.
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
public DatePickerFragment() {
}
private String selectedDate = "";
private Interfaces.OnDateSelectedClickListener onDateSelectedClickListener;
public DatePickerFragment(Interfaces.OnDateSelectedClickListener onDateSelectedClickListener, String selectedDate) {
this.onDateSelectedClickListener = onDateSelectedClickListener;
this.selectedDate = selectedDate;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar calendar = Calendar.getInstance();
int year = 0, month = 0, day = 0;
if (StaticUtils.isTextEmpty(selectedDate)) {
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
} else {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.getDefault());
Date date = simpleDateFormat.parse(selectedDate);
calendar.setTimeInMillis(date.getTime());
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
} catch (ParseException e) {
e.printStackTrace();
}
}
DatePickerDialog datePicker;
if (Build.VERSION.SDK_INT < 21) {
datePicker = new DatePickerDialog(getActivity(), AlertDialog.THEME_HOLO_LIGHT, this, year, month, day);
} else {
datePicker = new DatePickerDialog(getActivity(), R.style.datepicker, this, year, month, day);
}
datePicker.getDatePicker().setMaxDate(System.currentTimeMillis()); // disable future dates
datePicker.setTitle("");
datePicker.setCustomTitle(null);
return datePicker;
}
public void onDateSet(DatePicker view, int year, int month, int day) {
if (onDateSelectedClickListener != null) {
onDateSelectedClickListener.onDateSelect(StaticUtils.getDateTimeFromCalendar(day, month, year));
}
}
}
Update :
After applying @Lalchand code I am able to select the current date if I have loaded my calendar with the previous date but still, in API Level 21 it is not working. Can anyone help me? Or give me the suggestion to improve my code.