6

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.

e4c5
  • 52,766
  • 11
  • 101
  • 134
M.Almeida
  • 71
  • 1
  • 6

1 Answers1

5

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);
        }
    }
}
e4c5
  • 52,766
  • 11
  • 101
  • 134
  • The code works, but it also reloads WebView everytime you switch back to it from another app or kill and open it again. How can I stop that? –  Feb 02 '18 at 10:09
  • Unfortunately, this doesn't support back navigation, meaning that if user has navigated through `A>B>C>D`, after process kill only `D` will be saved, hence after restoration user won't be able to navigate to `C>B>A`. – azizbekian Jun 06 '19 at 14:19