Yasin Kaçmaz Yasin Kaçmaz - 4 months ago 14
Android Question

Android calendar changing time changing date to today

I am using

Calendar
and I am able to set date and get date for future. Assume that I have one
DatePickerDialog
which sets date for example 15-09-2016 and I have one
TimePickerDialog
which sets hour for example : 22:30

My problem is when I use
DatePickerDialog
and set date to : 15-09-2016 it's ok. But, then I use
TimePickerDialog
and try to change time,
Calendar's
date is changing to today (27-07-2016).

But if I use
TimePickerDialog
firstly then use
DatePickerDialog
there is no issue and I am able to set date : 15-09-2016 22:30

I checked Google and Stackoverflow and looked suggested questions when creating this question but i didnt see anything.

My
DatePickerDialog
:

DatePickerDialog datePickerDialog=
new DatePickerDialog(thisActivity, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mCalendarAlarm.set(Calendar.YEAR, year);
mCalendarAlarm.set(Calendar.MONTH, monthOfYear);
mCalendarAlarm.set(Calendar.DAY_OF_MONTH, dayOfMonth);
SimpleDateFormat dateformat = new SimpleDateFormat("dd MMM yyyy kk:mm",Locale.getDefault());
String datetime = dateformat.format(mCalendarAlarm.getTime());
alarmDate.setText(datetime);
}}, mCalendarAlarm.get(Calendar.YEAR), mCalendarAlarm.get(Calendar.MONTH),
mCalendarAlarm.get(Calendar.DAY_OF_MONTH));

datePickerDialog.getDatePicker().setMinDate(mCalendarAlarm.getTimeInMillis());
datePickerDialog.show();


My
TimePickerDialog
:

TimePickerDialog mTimePicker;
int hour = mCalendarAlarm.get(Calendar.HOUR_OF_DAY);
int minute = mCalendarAlarm.get(Calendar.MINUTE);
mTimePicker = new TimePickerDialog(thisActivity,mPickerTheme, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
mCalendarAlarm.set(Calendar.HOUR_OF_DAY,selectedHour);
mCalendarAlarm.set(Calendar.MINUTE,selectedMinute);
alarmDialogTime.setText(String.format(Locale.getDefault(),"%02d:%02d", selectedHour, selectedMinute));
}}, hour, minute, true);
mTimePicker.show();


When declaring
Calendar
:

mCalendarAlarm = Calendar.getInstance();
mCalendarAlarm.setTimeZone(TimeZone.getDefault());


So how can I solve this issue , is there a way or you guys meet this issue before. Thanks for help !

Answer

The issue is you are using same calendar object mCalendarAlarm for both Time and Date picker. Try to use different object of Calendar class for both pickers.

For example:

mCalendarAlarm for DatePicker and Create new Calendar object mTimeAlaram for TimePicker