Toydor Toydor - 1 month ago 15
Android Question

Android: NullPointerException in dialog when rotating

Sorry if this been asked before but I couldn't find an answer to my specific case. Also sorry that I'm new and a little stupid.

Problem:
I'm showing a dialog from a fragment and passing along a context in my constructor method because I need a context in my dialog to register for broadcastrecievers etc.

DialogFragment fragmentDialog = MyDialog.myConstructor(getActivity());
fragmentDialog.show(getFragmentManager(), "dialog");


Then in MyDialog class I store the context in a instance variable.
The problem arises when rotating the device and I get a nullPointerException when I try to use the context again in the dialog.

Can this be solved in some easy way?

Answer

If the device is rotated the Activity will be destroyed and recreated. So the Context you passed to your Fragment points on the Activity which was destroyed.

You could use setRetainInstance(true) in your Fragment. This way your Fragment will survive the recreation of the Activity.

To solve the NPE you have to pass the Context to the Fragment, if the Activity is recreated. Then the Context belongs to the new Activity.

In fact, without this update every line of code which points on the Activity like getActivity() or getFragmentManager() will lead in a NPE.