Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Android 4.1 Emulator Invoking onDateSet Twice from DatePicker Dialog

My application was working perfectly on my Android 2.2 emulator. I then decided to test on an Android 4.1 emulator. The DatePickerDialog looks a little different and for some reason when I press on "Done", the onDateSet() listener gets called twice and causes problems in my application.

I know this because the log shown below in the code is printed twice whenever I click on "Done"

mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            Log.v("onDateSet", "ENTERED");
            //rest of code...
    }};

Android 2.2 DatePicker

Working Android 2.2 DatePicker

Android 4.1 DatePicker

Not Working Android 4.1 DatePicker

like image 707
Nouran H Avatar asked Jul 08 '12 13:07

Nouran H


2 Answers

Try setting a boolean to check for a double fire within the same dialog. Something similar to:

Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_YEAR, 1);
final DatePickerDialog dateDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
    boolean fired = false;
    public void onDateSet(final DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {
        Log.i("PEW PEW", "Double fire check");
        if (fired) {
            Log.i("PEW PEW", "Double fire occured. Silently-ish returning");
            return;
        } else {
            //first time fired
            fired = true;
        }
        //Normal date picking logic goes here
    }
}, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
dateDialog.show();

This double fire issue also happens with onTimeSet of a TimePickerDialog and this check also works for those.

like image 167
lodlock Avatar answered Oct 16 '22 15:10

lodlock


According to Ankur Chaudhary's brilliant answer on the similar TimePickerDialog issue, if we checked inside onDateSet if the given view isShown() or not, it will solve the whole issue with the minimal effort, with no need for extending the picker or checking for some hideous flags going around the code or even checking for the OS version, just do the following:

public void onDateSet(DatePicker view, int year, int month, int day) {
    if (view.isShown()) {
        // read the date here :)
    }
}

and of course the same can be done for onTimeSet as per Ankur's answer

like image 29
AbdelHady Avatar answered Oct 16 '22 15:10

AbdelHady