0

seems that Android WebView doesn't store the cookies, how do I enable them?

I used this code to test it:

        webView = (WebView) findViewById(R.id.webView);
        webView.setWebViewClient(new WebViewClient());

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);

        webView.loadUrl("http://www.w3schools.com/php/showphp.asp?filename=demo_cookie1");

After I reload (webView.reload()) the page I do see "Cookie 'user' is set!" but after I close the application and start it again I see "Cookie 'user' is NOT set!". Weirdly enough sometimes I do see it set when I first start the app. So what's going on here? Is there a delay when cookies are stored or am I missing something?

Thanks!

2 Answers 2

6

+1 for eXistenZ' answer, but now in 2020 CookieSyncManager is deprecated. Now you should use CookieManager.getInstance().flush() or write something like this:

webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                CookieManager.getInstance().flush();
            } else {
                CookieSyncManager.getInstance().sync();
            } 
        }
}); 
1
  • working like charm. Thanks :)))
    – Ucdemir
    Jan 28, 2022 at 12:38
4

Seems that there is a delay indeed with the cookies so I have to use this code:

        webView.setWebViewClient(new WebViewClient() {
               public void onPageFinished(WebView view, String url) {
                   CookieSyncManager.getInstance().sync();
                   Toast.makeText(getApplicationContext(), "Page loading complete", Toast.LENGTH_LONG).show();
               }
        });

Now it works fine.

1
  • 1
    6 years on, this is still the case. WebView cookies indeed don't get saved when the app is terminated too soon. Thanks for the solution!
    – Aloha
    Apr 26, 2021 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.