Reputation: 346
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!
Upvotes: 0
Views: 4887
Reputation: 655
+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();
}
}
});
Upvotes: 6
Reputation: 346
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.
Upvotes: 4