John John - 24 days ago 9
Android Question

Show DatePickerDialog in DialogFragment

Is it possible to add a DatePickerDialog on top of a DialogFragment?

I have a DialogFragment with an EditText for adding date. When onFocus, I want it to show a DatePickerDialog. For my current implementation, it crashes when the application tries to show the DatePickerDialog.

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application


public class AddProjectDialogFragment extends DialogFragment {
private Context mContext;

public AddProjectDialogFragment() {
// Required empty public constructor
}

public static AddProjectDialogFragment newInstance() {
return new AddProjectDialogFragment();
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_add_project_dialog, container, false);
mContext = getActivity().getApplicationContext();
configureView(view);

return view;
}

private void configureView(View view) {
TextInputEditText projectNameET = (TextInputEditText) view.findViewById(R.id.project_name_et);
final EditText dateET = (EditText) view.findViewById(R.id.date_picker_et);
AppCompatButton addProjectBtn = (AppCompatButton) view.findViewById(R.id.add_project_btn);

final Calendar cal = Calendar.getInstance();
final DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
String dateFormat = "dd/MM/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.ENGLISH);
dateET.setText(sdf.format(cal.getTime()));
}
};

dateET.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
DatePickerDialog dpd = new DatePickerDialog(mContext, dateSetListener,
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH));

if (b) {
dpd.show();
} else {
dpd.dismiss();
}
}
});
}
}

Answer

You are getting WindowManager$BadTokenException, so you have to use

 mContext = getActivity();

remove getApplicationContext() from your mContext

or

You can also use like this, its working in my side

 dateET.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            DatePickerDialog dpd = new DatePickerDialog(getActivity(), dateSetListener,
                    cal.get(Calendar.YEAR),
                    cal.get(Calendar.MONTH),
                    cal.get(Calendar.DAY_OF_MONTH));

            if (b) {
                dpd.show();
            } else {
                dpd.dismiss();
            }
        }
    });