How to Download HTML or TXT Files from LocalStorage Content Using a WebView in an Android App

In this blog post, we'll explore how to download data stored in local storage as HTML or TXT files using a WebView in an Android app. This is particularly useful for saving user data or creating downloadable content from your web-based application within your Android app. Let's dive into the details!

Prerequisites

To follow along with this tutorial, you will need:

  • Android Studio installed on your computer
  • Basic knowledge of Java and Android development
  • A sample HTML file to load into the WebView

Setting Up Your Android Project

Create a New Android Project

Open Android Studio and create a new project. Choose "Empty Activity" and follow the setup wizard to create your project.

Add Required Permissions

In your AndroidManifest.xml file, add the necessary permissions to access the internet and write to external storage:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

Design Your Layout

Open activity_main.xml and add a WebView to your layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
    

Accessing Local Storage Data

JavaScript Interface for Saving Files

Create a JavaScript interface to handle saving data as a text file or HTML file. This interface will allow JavaScript to call Java methods from the WebView.

public class WebAppInterface {
    Context mContext;

    WebAppInterface(Context c) {
        mContext = c;
    }

    @JavascriptInterface
    public void saveTxt(String data) {
        try {
            File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File file = new File(downloadsDir, "localstorage.txt");
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(data.getBytes());
            fos.close();
            Toast.makeText(mContext, "TXT file saved to Downloads", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void saveHtml(String data) {
        try {
            File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File file = new File(downloadsDir, "localstorage.html");
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(data.getBytes());
            fos.close();
            Toast.makeText(mContext, "HTML file saved to Downloads", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
    

Setting Up the WebView

In your MainActivity.java file, set up the WebView and add the JavaScript interface:

public class MainActivity extends AppCompatActivity {
    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new WebAppInterface(this), "AndroidInterface");
        webView.loadUrl("file:///android_asset/yourfile.html");
    }
}
    

JavaScript Code to Save Data

In your HTML file (yourfile.html), add the following JavaScript code to save the local storage data as TXT or HTML files:

<!DOCTYPE html>
<html>
<head>
    <title>LocalStorage Data</title>
</head>
<body>
    <script type="text/javascript">
        window.onload = function() {
            var data = localStorage.getItem('key');

            // Save as TXT
            if (data) {
                window.AndroidInterface.saveTxt(data);
            }

            // Save as HTML
            var htmlData = '<html><body>' + data + '</body></html>';
            if (data) {
                window.AndroidInterface.saveHtml(htmlData);
            }
        };
    </script>
</body>
</html>
    

Conclusion

With the above steps, you now have an Android app that can download local storage data as either a TXT file or an HTML file using a WebView. This method provides a seamless way to handle and save data directly from your web-based application running inside an Android WebView.

Feel free to customize the code to suit your specific needs. Happy coding!

0 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *


You may like to read


Follow Us

Sponsored Ads

GranNino Ads

Newsletter

Subscribe to our Newsletter to read our latest posts at first

We would not spam your inbox! Promise
Get In Touch

© Fullstack Coding Tips. All Rights Reserved.