saving webview into local storage automatically

Viewed 645

Webview loads every time I open it, Is there any way the web view files will be saved in local storage when I open the first time and when I open it again they don't need to be downloaded. means even if there is no internet they will open.

here's my java file. is there any way we can perform this task

package com.example.impwala;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;



public class chemistry1 extends AppCompatActivity {

    WebView chem1;
    ProgressDialog pDialog;

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

        if (haveNetwork())
        {
            init();
            listener();
        }
        else if (!haveNetwork())
        {
            AlertDialog.Builder builder =new AlertDialog.Builder(this);
            builder.setTitle("No internet Connection");
            builder.setMessage("Please turn on internet connection to continue");
            builder.setNegativeButton("close", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            AlertDialog alertDialog = builder.create();
            alertDialog.show();        }

    }

    public boolean haveNetwork()
    {
        boolean have_WIFI=false;
        boolean have_MobileData=false;

        ConnectivityManager connectivityManager=(ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo[] networkInfos=connectivityManager.getAllNetworkInfo();

        for (NetworkInfo info:networkInfos)
        {
            if (info.getTypeName().equalsIgnoreCase("WIFI"))
                if(info.isConnected())
                    have_WIFI=true;
            if (info.getTypeName().equalsIgnoreCase("MOBILE"))
                if(info.isConnected())
                    have_MobileData=true;
        }
        return have_MobileData||have_WIFI;
    }
    private void init() {

        chem1 = (WebView) findViewById(R.id.chem1);
        chem1.getSettings().setJavaScriptEnabled(true);

        pDialog = new ProgressDialog(chemistry1.this);
        pDialog.setTitle("PDF");
        pDialog.setMessage("Loading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        chem1.loadUrl("www.example.com");

    }


    private void listener() {
        chem1.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                pDialog.show();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                pDialog.dismiss();
            }
        });
    }
}

1 Answers

Save your page as a web archive to your SD card storage in public Documents folder as,

File file;
String filenameExternal = "mypage";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED{
         file = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOCUMENTS), filenameExternal);
}

chem1.saveWebArchive(file.toString()+".mht");

then, save the file name/path using shared preferences when the user leaves the app by overriding @OnStop method. Finally, load your saved page by reading the file path from shared preference when the user re-opens the app.

if (Build.VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
                    chem1.loadUrl(file.toString()+".mht");
                } else {

                    loadOfflinePageBelowKitKat(position);
                } 

loadOfflinePageBelowKitKat method

public void loadOfflinePageBelowKitKat(){

    String rawData = null;
    try{
        rawData = getStringFromFile(file.toString()+".mht");
    }catch (Exception e){
        e.printStackTrace();
    }

    chem1.loadDataWithBaseURL(null, rawData, "application/x-webarchive-xml", "UTF-8", null);

}

getStringFromFile method

public String getStringFromFile(String filePath) throws Exception{
    File file = new File(filePath);
    FileInputStream fInputStream = new FileInputStream(file);
    String wantedString = convertStreamToString(fInputStream);
    fInputStream.close();
    return  wantedString;
}

I assumed you're familiar with working on shared preferences and Files.

Related