如何使用Webview访问现有数据库

时间:2019-01-04 12:41:08

标签: javascript android cordova webview

这是我打开Webview的方式

myWebView = (WebView) this.findViewById(R.id.webView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
myWebView.addJavascriptInterface(this, "android");
myWebView.requestFocusFromTouch();
myWebView.setWebViewClient(new WebViewClient());
myWebView.setWebChromeClient(new WebChromeClient());
final String databasePath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
webSettings.setDatabasePath(databasePath);
webSettings.setAppCacheMaxSize(5 * 1024 * 1024);
webSettings.setDatabaseEnabled(true);
webSettings.setLoadsImagesAutomatically(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadsImagesAutomatically(true);
webSettings.setAppCacheEnabled(true);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
webSettings.setAllowFileAccess(false);
webSettings.setUseWideViewPort(false);
webSettings.setSupportZoom(false);
webSettings.setSavePassword(false);
webSettings.setSupportMultipleWindows(false);

myWebView.setWebChromeClient(new WebChromeClient() {
    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        super.onProgressChanged(view, newProgress);
    }

    @Override
    public void onExceededDatabaseQuota(String url,
                                        String databaseIdentifier, long currentQuota,
                                        long estimatedSize, long totalUsedQuota,
                                        WebStorage.QuotaUpdater quotaUpdater) {
        quotaUpdater.updateQuota(5 * 1024 * 1024);
    }


    @Override
    public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
        Log.e("MyApplication", consoleMessage.message() + " -- From line "
                + consoleMessage.lineNumber() + " of "
                + consoleMessage.sourceId());
        return super.onConsoleMessage(consoleMessage);
    }
});


myWebView.loadUrl(sync_link);

及其加载,这是我在webview中的JS

function loaddb(){
    var db = openDatabase('test', '1.0', 'test', 2 * 1024 * 1024);
    db.transaction(function (tx) {
        tx.executeSql('SELECT * FROM test LIMIT 10', [],
            function (tx, results) {
                for (var i = 0; i < results.rows.length; i++) {
                    var row = results.rows.item(i);
                    var stringout = "Category: " + row['test1'];
                    document.getElementById('mobileWraper').innerHTML = stringout;
                }
            },
            globalError
        );
    });
}

function globalError(tx, error){
  document.getElementById('mobileWraper').innerHTML = "Error: " + error.message;
}

整个代码都在工作,但是我收到一条错误消息,说该表不存在。我的问题是我的android应用在安装过程中创建了一个数据库,我该如何访问它?通常由android应用创建的Database文件夹中的数据库

0 个答案:

没有答案