AJW
AJW

Reputation: 1649

How do I reference findFragmentByTag to re-display a softkeyboard?

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). The InputMethodManager to launch the soft keyboard uses "getActivity()" reference which I think is causing the crash after orientation since the Activity is re-created. Can I replace that with a reference to the Fragment using findFragmentByTag as a way to re-use the dialogfragment upon orientation change?

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);
}

}

Activity file // uses show() to launch the DialogFragment:

public class Activity extends AppCompatActivity {
...
DatePickerFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");

Upvotes: 0

Views: 23

Answers (1)

Elltz
Elltz

Reputation: 10859

check if getActivity() is not null in your onDismiss()

Upvotes: 1

Related Questions