Home » Android » android – onSaveInstanceState and Fragments?

android – onSaveInstanceState and Fragments?

Posted by: admin May 14, 2020 Leave a comment

Questions:

How can I get a fragment to save it’s state? I’ve tried everything but no luck, nothing is working.

Ive tried adding:

public void onSaveInstanceState(Bundle outState) {
   super.onSaveInstanceState(outState);
   myWebView.saveState(outState);
   Log.w("///////", "onSaveInstanceState");

}

But this never gets called.

Any ideas?


I’m now trying to restore the state of the web view:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

     View mainView = (View) inflater.inflate(R.layout.frag_b, container, false);
     myWebView = (WebView) mainView.findViewById(R.id.webviewtest);
     myWebView.setWebViewClient(new MyWebViewClient());
     myWebView.getSettings().setPluginsEnabled(true);
     myWebView.getSettings().setBuiltInZoomControls(false); 
     myWebView.getSettings().setSupportZoom(false);
     myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);   
     myWebView.getSettings().setAllowFileAccess(true); 
     myWebView.getSettings().setDomStorageEnabled(true);
     myWebView.loadUrl("http://www.google.com");   
     myWebView.setId(1);
     myWebView.restoreState(savedInstanceState);
     Log.w("///////", "onCreateView");

    return mainView;
}

But the above doesnt work, any ideas?

How to&Answers:

Have you looked into this: Fragment's onSaveInstanceState() is never called

You need to make sure to call super.onSaveInstanceState(Bundle) in your FragmentActivity.