I have a Fragment
(used support library) like this
public class ItemDetailsFragment extends Fragment {
private ListView itemsListView;
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
itemsListView = (ListView) view.findViewById(R.id.listMode);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
ItemsAdapter adapter = (ItemsAdapter) itemsListView.getAdapter();
ArrayList<String> items = adapter.getItems();
outState.putStringArrayList("some_key", items);
}
}
Note that itemsListView
is initialized properly. and when I set Adapter to this ListView, ListView is showing items properly. but when I call
itemsListView.getAdapter();
in onSaveInstanceState
callback, I am getting NPE and I recognized that itemsListView
is null
while debugging. I am confident that I am not assigning itemsListView
to null
through out the Fragment
. More over, I am getting this NPE error only sometimes but I am unable to say when it is.
Where the error might be? why itemsListView
is becoming null
only some times?
Thanks to all...
Note that onSaveInstanceState() is called when your activity goes into the background and NOT when the app process is about to be killed.
Various Android system operations can affect the state of your fragment. To ensure the user's state is saved, the Android framework automatically saves and restores the fragments and the back stack. Therefore, you need to ensure that any data in your fragment is saved and restored as well.
onSaveInstanceState(): In order to save sates of UI, I override onSaveInstanceState(Bundle savedInstanceState) and save all the data of the UI in savedInstanceState Bundle. This method is called before onStop() in older versions of Android (till android 8.0) and can be called after onStop() for newer versions.
A fragment life cycle is closely related to the lifecycle of its host activity which means when the activity is in the pause state, all the fragments available in the activity will also stop. Fragments added to the Android API in Android 3.0 which API version 11 to support flexible UI on large screens.
There is a note in Android documentation on onSaveInstanceState
fragments:
This corresponds to Activity.onSaveInstanceState(Bundle) and most of the discussion there applies here as well. Note however: this method may be called at any time before onDestroy(). There are many situations where a fragment may be mostly torn down (such as when placed on the back stack with no UI showing), but its state will not be saved until its owning activity actually needs to save its state.
It makes using onSaveInstanceState
methods for fragments rather tricky.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With