Skip to content Skip to sidebar Skip to footer

Showing TimePickerDialog Fragment Error

I am trying to launch a timepicker from a button in a fragment I've read post regarding the same problems about the Error but the codes doesn't match on what I have started thats w

Solution 1:

MainActivity cannot be cast to android.app.TimePickerDialog$OnTimeSetListener

Which means you can not call a method which is declared in the subclass.

Problem coming form

 android.support.v4.app.DialogFragment timePicker = new TimePickerFragment(); 

Try with

TimePickerFragment  timePicker = new TimePickerFragment ();
timePicker.show(getActivity().getSupportFragmentManager(), "time picker");

"Cannot Resolve Method 'getSupportFragmentManager()'"

Make sure your ROOT Activity extends

  • AppCompatActivity/FragmentActivity

Did you using ?

import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

Solution 2:

About the

MainActivity cannot be cast to android.app.TimePickerDialog$OnTimeSetListener

it is happening because you are trying to cast your activity to OnTimeSetListener

return new TimePickerDialog(getActivity(),(TimePickerDialog.OnTimeSetListener) getActivity(), cHour, cMinute, android.text.format.DateFormat.is24HourFormat(getActivity()));

Make sure that your activity is extending the OnTimeSetListener, and if it so, you may try to convert right to your activity

return new TimePickerDialog(getActivity(),(MainActivity) getActivity(), cHour, cMinute, android.text.format.DateFormat.is24HourFormat(getActivity()));

because your activity will be a instance of OnTimeSetListener.

Also, I do not recommend using the getActivity() to get the listener from your fragment, its better if you have your listener not attached to your activity.


Solution 3:

Use getParentFragment() instead of getActivity().


Post a Comment for "Showing TimePickerDialog Fragment Error"