5

I am experimenting with Android code: I would like to store one value using HTML 5 local storage. For this exercise I' using a page as simple as this one: http://www.w3schools.com/html5/tryit.asp?filename=tryhtml5_webstorage_local_clickcount

My manifest does allow me to hit the internet, and it is min-sdk of 7.

Here is my java code:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    webview = (WebView) findViewById(R.id.webview);
    WebView webView = (WebView) findViewById(R.id.webview);
    webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
    WebSettings webSettings = webview.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDatabasePath("");
    webSettings.setDomStorageEnabled(true);
    webview.setWebChromeClient(new WebChromeClient());
    webview.loadUrl("http://www.xyz.com/test.html");
    ///xyz.com/test.html is a sample  :)
    webview.setWebViewClient(new HelloWebViewClient());
}

My problem is that when I close the app, the locally stored value is no longer there. I can browse to the same page using the default browser, and the value is persistent even after closing the emulator, which is exactly the behavior that I am looking for.

This is probably a something extremely simple....any ideas?

MrM
  • 85
  • 1
  • 3
  • 12

3 Answers3

7

It appears the empty string DatabasePath is the problem. I tried similar code and with an empty string path, the value does not persist after the app exits. If I define a specific database path, the value persists as expected.

Try:

webSettings.setDatabasePath("/data/data/"+this.getPackageName()+"/databases/");
Robert Nekic
  • 3,087
  • 3
  • 24
  • 36
2

If your app use multiple webview you will still have troubles : localStorage is not correctly shared accross all webviews.

If you want to share the same data in multiple webviews the only way is to repair it with a java database and a javascript interface.

This page on github shows how to do this.

hope this help!

Guillaume Gendre
  • 2,504
  • 28
  • 17
  • I also would like to mention that there is an hybrid framework, Cobalt (http://cobaltians.org) that could help you manage multiple webviews in your native apps. it is a tool for both native and web developpers. you should check it out. – Guillaume Gendre Mar 22 '16 at 14:51
1

Couldn't get it working on all devices (especially with ICS) - even with database path, enabling DOMStorage etc. - using cookies instead helped me out.

Piotr
  • 1,743
  • 1
  • 26
  • 40