Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webview is not restoring the state after it was killed by the user

i've been in a trouble for some days to understand this issue. Basically i have a Webview which loads a website, with the first page being the login and the content follows after the login.

Every user validation is made through the site it self. So there is nothing to be saved in a SharedPreference for example. Im only using the url in this scenario.

so onCreate after killing my app , the webview is not restoring the previous state before it was killed.

I suppose its because the savedinstancestate is coming null, and is loading the url again after the app being killed.

I have the session cookies and other stuff.

i was wondering if someone has some suggestion.

p.s.I'm new in Android.

like image 223
M.Almeida Avatar asked Sep 28 '15 22:09

M.Almeida


1 Answers

As you yourself pointed out since the saved state is null, you cannot possibly expect onCreate to take your webview back to the last page that was open. There are two things that you need to do:

Make sure that your login page, which is your first page redirects to a relevent content page when it detects that the user has already logged in. Since you are already using cookies this is trivial.

Then over ride the onPause method to save the current url of the webView.

@Override
protected void onPause() {
    super.onPause();
    SharedPreferences prefs = context.getApplicationContext().
            getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
    Editor edit = prefs.edit();
    edit.put("lastUrl",webView.getUrl());
    edit.commit();   // can use edit.apply() but in this case commit is better
}

Then you can read this property on the onCreate method and load the url as needed. If the preference is defined load it, if not load the login page (which should redirect to first content page if already logged in)

UPDATE here's what your onResume might look like. Also added one line to the above onPause() method.

@Override
protected void onResume() {
    super.onResume();
    if(webView != null) {
        SharedPreferences prefs = context.getApplicationContext().
            getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
        String s = prefs.getString("lastUrl","");
        if(!s.equals("")) {
             webView.loadUrl(s);
        }
    }
}
like image 134
e4c5 Avatar answered Nov 07 '22 10:11

e4c5