Search code examples
androiddatepickertimepicker

DatePicker and TimePicker code not working together ("protected Dialog onCreateDialog(int id)" is already defined)


I have created an app, in which I have a DatePicker and a TimePicker. First I made the Datepicker and I displayed it when I selected the Date textview, this worked perfectly fine. Then I wanted to do the same for the Time EditText but instead of displaying a DatePicker it is supposed to display a TimePicker when selected.

After I implemented the code for the TimePicker: The error is that the "protected Dialog onCreateDialog(int id)" is already defined and I cannot use this method twice.

Any help would be appreciated,

Thanks in Advance


Solution

  • I assume that you have only one DialogFragment for both date and time pickers... this will create a conflict as you have already implemented the onCreateDialog.

    what I usually do is I create another class for each component that i would like to have a different implementation of onCreateDialog.

    public class DatePickerDialog  extends DialogFragment implements DatePickerDialog.OnDateSetListener{
            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
              ...
            }
    
    
    
     public class TimePickerDialog  extends DialogFragment implements 
        TimePickerDialog.OnTimeSetListener{
                    @Override
                    public Dialog onCreateDialog(Bundle savedInstanceState) {
                      ...
                    }
    

    then I would call it in the activity like ...

    DatePickerDialog dialog = new DatePickerDialog();
    FragmentManager fm = getSupportFragmentManager();
    dialog.show(fm, "Date Picker");
    

    this way you could also add custom callbacks or listeners for each picker and use them multiple times in one activity.