I have a DatePickerDialog that launches successfully in a fragment. When an orientation change occurs the app crashes. The logcat output says the NPE happens with onDismiss in the DatePickerFragment. The onDismiss code is used to toggle the soft keyboard to show again (after the launch of the DatePickerDialog toggles it off). When I remove the onDismiss code the app no longer crashes. What am I missing here?
Here is partial DatePickerFragement file:
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
public DatePickerFragment() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
...
DatePickerDialog picker = new DatePickerDialog(getActivity(),
this, year, month, day);
return picker;
}
public void onDismiss(final DialogInterface dialog) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(CardViewActivity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
super.onDismiss(dialog);
}
}
This is another fragment I have that handles orientation change with no crashes and keyboard toggles back on correctly:
public class CreateSkycardFragment extends DialogFragment {
public CreateSkycardFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.skyfrag_layout, container, false);
getDialog().setTitle("Delete card");
Button btnCancel = (Button) rootView.findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(CardViewActivity.INPUT_METHOD_SERVICE);
// The soft keyboard always closes when the DialogFragment is displayed. So the
// line below toggles the soft keyboard to show again.
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
// The line below cancels the dialog box.
getDialog().cancel();
}
});
// When the user clicks "OK" to delete for the "Delete skycard" dialog.
Button btnOK = (Button) rootView.findViewById(R.id.btnOK);
btnOK.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Next line dismisses the DialogFragment
dismiss();
// Next line returns to the previous activity (MainActivity) by closing
// the current activity (CardViewActivity).
getActivity().finish();
}
});
getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(android.content.DialogInterface dialog, int keyCode, KeyEvent event) {
if ((keyCode == android.view.KeyEvent.KEYCODE_BACK)) {
if (event.getAction()!= KeyEvent.ACTION_DOWN)
// Next line dismisses the dialogfragment
dismiss();
// Next line returns to the previous activity (MainActivity) by closing the fragment and
// the current activity (CardViewActivity).
getActivity().finish();
return true;
}
return false;
}
});
return rootView;
}
}