194
votes

I have a local html page along with several other resources pointed by it (css files and Javascript libraries) that I would like to load into a WebView . How could this be achieved ?

Perhaps not the best way to procede but I'm still experimenting.

5
for me it worked if I dropped the dot html -webView.loadUrl("file:///android_asset/filename"); - quemeful
Any reason why you don't want to accept @Joe's answer? - ClassA

5 Answers

358
votes

The easiest way would probably be to put your web resources into the assets folder then call:

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

For Complete Communication between Java and Webview See This

Update: The assets folder is usually the following folder: <project>/src/main/assets This can be changed in the asset folder configuration setting in your <app>.iml file as:

<option name=”ASSETS_FOLDER_RELATIVE_PATH” value=”/src/main/assets” /> See Article Where to place the assets folder in Android Studio

28
votes

probably this sample could help:

  WebView lWebView = (WebView)findViewById(R.id.webView);
  File lFile = new File(Environment.getExternalStorageDirectory() + "<FOLDER_PATH_TO_FILE>/<FILE_NAME>");
  lWebView.loadUrl("file:///" + lFile.getAbsolutePath());
6
votes

In this case, using WebView#loadDataWithBaseUrl() is better than WebView#loadUrl()!

webView.loadDataWithBaseURL(url, 
        data,
        "text/html",
        "utf-8",
        null);

url: url/path String pointing to the directory all your JavaScript files and html links have their origin. If null, it's about:blank. data: String containing your hmtl file, read with BufferedReader for example

More info: WebView.loadDataWithBaseURL(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)

0
votes

The Accepted Answer is not working for me, This is what works for me

WebSettings webSetting = webView.getSettings();
    webSetting.setBuiltInZoomControls(true);
    webView1.setWebViewClient(new WebViewClient());

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

XML Layout File:

<WebView android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/webView"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".activities.Bani9">
</WebView>

Java Code:

public class Bani9 extends AppCompatActivity {
    WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bani9);
        webView = findViewById(R.id.webView);
        WebSettings webSetting = webView.getSettings();
        webSetting.setBuiltInZoomControls(true);
        webView.setWebViewClient(new WebViewClient());

        webView.loadUrl("file:///android_asset/punjabi/bani9.html");
    }
}

Make sure you set file path accurately. Make sure you set File Path properly