Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment's onSaveInstanceState() is never called

I'm trying to save data in a Fragment's onSaveInstanceState(), but the method is never called.

Can someone help?

public class MyFragment extends Fragment {      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {         ScrollView content = (ScrollView) inflater.inflate(R.layout.content, container, false);         // More stuff         return content;     }      @Override     public void onSaveInstanceState(Bundle icicle) {         // NEVER CALLED         super.onSaveInstanceState(icicle);         //More stuff     }  } 
like image 933
jul Avatar asked Dec 14 '11 11:12

jul


People also ask

When onSaveInstanceState is called in Fragment?

java. In that fragment I use onSaveInstanceState and onCreate method.In onCreate method I supposed to clear sharedPreferences if there is no bundle passed from onSaveInstanceState, if onSaveInstanceState pass a bundle I would not need to clear sharedPreferences.

What is the purpose of using onSaveInstanceState () here?

Basically, onSaveInstanceState is used for the scenario where Android kills off your activity to reclaim memory. In that scenario, the OS will keep a record of your activity's presence, in case the user returns to it, and it will then pass the Bundle from onSaveInstanceState to your onCreate method.

When onviewcreated is called?

onCreate(Bundle) called to do initial creation of the fragment. onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment. onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity. onCreate() .

When should I call onSaveInstanceState?

Note that onSaveInstanceState() is called when your activity goes into the background and NOT when the app process is about to be killed.


1 Answers

I finally figured out the problem, at least in my case. I had an overridden onSaveInstanceState in my FragmentActivity that did not call super.onSaveInstanceState(Bundle outState). Once I added that in, the Fragment.onSaveInstanceState(Bundle outState) functioned normally.

like image 149
James Avatar answered Oct 23 '22 12:10

James