Search code examples
androidtimepicker

OnTimeSet called also when dismissing TimePickerDialog


Today I was trying to use the TimePickerDialog but I noticed a couple of flaws.

  1. OnTimeSet is called also when the dialog is dismissed (by clicking outside, for example)
  2. OnTimeSet is called twice when the user taps the "Done" button

The API I'm using is 18.

Anyone else has experienced these problems? How did you solve them?


Solution

  • Faced the exact same issue today. Could not figure out why this was happening, but found a simple solution:

    Method onTimeSet() is called once when dialog is dismissed and is called twice when Done button is clicked. Either way, there is one unwanted call to onTimeSet(). So I decided to always ignore the first call.

    Here's the code:

    Calendar mcurrentTime = Calendar.getInstance();
    int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
    int minute = mcurrentTime.get(Calendar.MINUTE);
    
    TimePickerDialog mTimePicker;
    mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() 
        {
            int callCount = 0;   //To track number of calls to onTimeSet()
    
            @Override
            public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) 
            {
                 if(callCount == 1)    // On second call
                 {
                     timeString = selectedHour + ":" + selectedMinute + ":00";
                     Log.d("TEST", "Chosen time : "+ timeString);           
                 }
    
                 callCount++;    // Incrementing call count.
    
            }
        }, hour, minute, true);
    
        mTimePicker.setTitle("Pick Time");
        mTimePicker.show();