如何在Android Studio webview中本地保存数据

时间:2017-03-07 23:58:06

标签: android android-studio webview

我看到论坛上有很多关于这个问题的问题,但我不认为这个问题适用于我的案例。我通过Android Studio的WebView开发应用程序,让您在线购物。应用程序必须在启动时收集名称,电话和客户端地址。然后,在本地写入数据以将其用作参考,以便稍后在数据库中保存。我使用此命令在本地保存数据:

  

localStorage.setItem(' name',' John');

但它与Android Studio不兼容,因此我将其添加到MainActivity:

  

settings.setDatabaseEnabled(真);

即便如此,我也无法在本地保存数据。在这种情况下,有没有办法在本地保存和提取数据?

MainActivity的代码是:

WebView webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("file:///android_asset/www/index.html");
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDatabaseEnabled(true);
String databasePath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();

1 个答案:

答案 0 :(得分:0)

public class MyActivity extends Activity {
    WebView webView = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Get rid of the android title bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);

        webView  = (WebView) findViewById(R.id.main_webview);
        WebSettings settings = webView.getSettings();

    //Enable Javascript
        settings.setJavaScriptEnabled(true);

    //Enable DOM storage, and tell Android where to save the Database
        settings.setDatabasePath("/data/data/"+this.getPackageName()+"/databases/");
        settings.setDomStorageEnabled(true);

        webView.loadUrl("file:///android_asset/index.html");

        webView.setWebChromeClient(new WebChromeClient() {

            /** Called when the database exceeds it's maximum size **/
            @Override
            public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
            //Double the estimated size of the Database
               quotaUpdater.updateQuota(estimatedSize * 2);
        } 
        });
    }
}