Android webView saveState-ThrowExceptions

Exception or error:

I have a tabhost with 3 tabs. In each of these tabs there is a webiview.
When i click a tab the webview need to “reload” even when i have been there before, it have not been saved.
Is there any way to save the webview ?

How to solve:

This can be handled by overrwriting onSaveInstanceState(Bundle outState) in your activity and calling saveState from the webview:

@Override
protected void onSaveInstanceState(Bundle outState) {
    webView.saveState(outState);
    super.onSaveInstanceState(outState); 
}

Then recover this in your onCreate after the webview has been re-inflated of course:

@Override
public void onCreate(final Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.blah);
   WebView webview = (WebView)findViewById(R.id.webview);
   if (savedInstanceState != null)
      webview.restoreState(savedInstanceState);
   else
      webview.loadUrl(URLData)
}

###

restoreState was never reliable. And come 2015 the documents accept the fact. (The change was probably made to the documents around 2014).
This is what it says now.

If it is called after this WebView has had a chance to build state
(load pages, create a back/forward list, etc.) there may be
undesirable side-effects. Please note that this method no longer
restores the display data for this WebView.

And the corresponding entry for saveState() speaks thus:

Please note that this method no longer stores the display data for
this WebView.

What you really should do inside the onCreate method is to call webView.loadUrl() if you want to display the last visited url, please see this answer:

If you are concerned about the webview reloading on orientation change etc.

you can set your Activity to handle the orientation and keyboardHidden changes, and then just leave the WebView alone

###

Alternatively you can look into using fragments with your tabHost. when entering another webView you can set fragment to hide and the other to show. when you return to the previous fragment the content will not have been destroyed. Thats how i did it and it worked for me.

Leave a Reply

Your email address will not be published. Required fields are marked *