Search code examples
androiddatepickerdialogdatetimepickertimepicker

code keeps running without proper sequence


In my code i have a date and time picker.... but for some reason the code doesn't wait till i pick anything and once the mDateSetListener dialog is shown the Log.d shows in the Logcat today's date. also the first time the dialog is shown, it doesn't show mTimeSetListener, and i have to request it for a second time for it to work properly here is my code

static void dateAndTimePicker(final Context context, final ListView selectedFood, final int type) {

    contextGlobal = context;
    dateTime = new int[5];
    cal = Calendar.getInstance();
    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH);
    int day = cal.get(Calendar.DAY_OF_MONTH);

    DatePickerDialog dialog = new DatePickerDialog(contextGlobal,
            android.R.style.Theme_Holo_Light_Dialog_MinWidth, mDateSetListener, year, month, day);
    Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    dialog.show();

    mDateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
            month = month + 1; /*january is 0 (months start with 0 not 1)*/
            Log.d("date is", month + "/" + day + "/" + year);
            dateTime[0] = year;
            dateTime[1] = month;
            dateTime[2] = day;
            hour = cal.get(Calendar.HOUR_OF_DAY);
            minute = cal.get(Calendar.MINUTE);

            TimePickerDialog timePickerDialog = new TimePickerDialog(contextGlobal,
                    android.R.style.Theme_Holo_Light_Dialog_MinWidth, mTimeSetListener, hour, minute, false);
            timePickerDialog.show();
        }

    };

    mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker timePicker, int hour, int minute) {
            Log.d("Time is", hour + ":" + minute);
            dateTime[3] = hour;
            dateTime[4] = minute;
            addFood(contextGlobal, dateTime, selectedFood, type);

        }
    };

    Log.d("date", String.valueOf(day));

}

thank you in advance


Solution

  • but for some reason, the code doesn't wait till I pick anything and once the mDateSetListener dialog is shown the Log.d shows in the Logcat today's date.

    It's because, onDateSet is some sort of asynchronous call (waits for the user to perform an action), and will only be triggered when a user taps the desired date form DatePickerDialog

    also the first time the dialog is shown, it doesn't show mTimeSetListener, and I have to request it for a second time for it to work properly

    -- -- --