4

I am trying to get this WebView for android code to keep session cookies so that when the app closes and users start it again they can stay logged in. I am very new at this and I am getting frustrated trying to figure this out. What do I need to change? Please be kind as I am an idiot, and please be descriptive, even if you have to edit it for me if that is easier for you.

I imported both CookieManager and CookieSyncManager but have NO IDEA what to do next. I have read all of the documentation and have spent hours trying to figure out how to make it save cookies so users don't have to login again and I just can't figure it out...

package com.template.WebViewTemplate;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

public class WebViewTemplate extends Activity {
private WebView myWebView;
/** Called when the activity is first created. */
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) { // Enables browsing to previous pages with the hardware back button
        myWebView.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
} 

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    myWebView = (WebView) findViewById(R.id.webview); // Create an instance of WebView and set it to the layout component created with id webview in main.xml
    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.loadUrl("http://zuneboards.com/forums/mgc_chatbox.php?do=view_chatbox"); // Specify the URL to load when the application starts
    //myWebView.loadUrl("file://sdcard/"); // Specify a local file to load when the application starts. Will only load file types WebView supports
    myWebView.setWebViewClient(new WebViewKeep());
    myWebView.setInitialScale(1); // Set the initial zoom scale
    myWebView.getSettings().setBuiltInZoomControls(true); // Initialize zoom controls for your WebView component
    myWebView.getSettings().setUseWideViewPort(true); // Initializes double-tap zoom control

}

private class WebViewKeep extends WebViewClient {
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }

}}

user1055675
  • 41
  • 1
  • 2
  • CookiesManager and android documentation described here [this post][1] [1]: http://stackoverflow.com/questions/2566485/webview-and-cookies-on-android – rachar_P Oct 15 '13 at 06:30

1 Answers1

5

You can Use this with Web settings :

webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

Also import:

import android.webkit.WebSettings;
import android.webkit.WebView;
Max Base
  • 639
  • 1
  • 7
  • 15
A-Droid Tech
  • 2,301
  • 24
  • 33