Home » Java » How to write and read file from WebView in Android?

How to write and read file from WebView in Android?

Posted by: admin October 24, 2018 Leave a comment

Questions:

I’m developing an Android app. In that app, I’m using WebView. I’m calling API in this WebView using HTML and javascript to get some data from the server. I want to write this data to an internal storage file on Android device and read this file data from javascript.

Java Code:

WebView browser = (WebView) this.findViewById(R.id.browser);
browser.getSettings().setJavaScriptEnabled(true);
browser.getSettings().setSupportMultipleWindows(true);
browser.getSettings().setDomStorageEnabled(true);
browser.getSettings().setDatabaseEnabled(true);
browser.addJavascriptInterface(new WebAppInterface(this), "Android");

browser.setWebChromeClient(new WebChromeClient(){

    @Override
    public void onReceivedTitle(WebView view, String title) {
        getWindow().setTitle(title); //Set Activity tile to page title.
    }
});

browser.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return false;
    }
});

browser.reload();
browser.loadUrl("file:///android_asset/www/index.html");

I think this problem can be solved in the below ways.

  1. Write and Read the file in JavaScript code, But I have no clue how to write and read the file on the internal storage of Android device using javascript. I’m not sure whether this is possible or not due to the security violation.

  2. Write to file in Java native code and read this file from javascript code. Reference: https://developer.android.com/training/data-storage/files

  3. Write to file in Java native code and read this file in java native code and pass the data to WebView( javascript). I have no idea how to implement this.

So Could you guys please suggest which is better and feasible approach.

Answers: