206

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.

Aashish Kumar
  • 2,771
  • 3
  • 28
  • 43
klaus johan
  • 4,370
  • 10
  • 39
  • 56

6 Answers6

374

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

ArtemGr
  • 11,684
  • 3
  • 52
  • 85
Joe
  • 4,801
  • 2
  • 16
  • 8
  • 6
    This problem is really an FAQ. – shihpeng Apr 21 '11 at 20:49
  • What other ways would there be ? – klaus johan Apr 21 '11 at 21:26
  • 2
    You could presumably also load it form a String if you're very adverse to using assets...(see http://stackoverflow.com/questions/4543349/load-local-html-in-webview) – Joe Apr 21 '11 at 21:36
  • 25
    This should be marked as correct answer, `cause it really is. – gorodechnyj Nov 21 '12 at 10:34
  • If the assets path ever changes this will break. – Ken Apr 26 '13 at 07:35
  • 6
    @SK9 The same applies if any other asset or expected file is missing, like if you change the name of your starting activity class and don't update `AndroidManifest.xml` to reflect that. (Personally, I'd recommend putting the URL/file path in string resources and accessing it from there such that the path is with all the other string data for the program, but that isn't really directly related to the issue of asset/resource dependency.) – JAB Jun 10 '13 at 14:46
  • for me it worked if I dropped the dot html -webView.loadUrl("file:///android_asset/filename"); – quemeful Feb 19 '15 at 14:33
  • 7
    For those don't know how to create assets folder, right click on "app"->"New"->"Folder"->"Assets Folder", and click "Finish". Android Studio will create the assets folder in correct path. And you just need to move your html file to the new assets folder. Reference: http://stackoverflow.com/questions/18302603/where-to-place-assets-folder-in-android-studio – Yuchao Zhou Aug 22 '16 at 22:24
  • Yes, this is working, but it shows incorrectly non english letters. – zygimantus Sep 18 '16 at 08:00
  • I have same problem for ios, does anyone have come across this problem? If yes please share your solution i tried different way to access but it of no use , i tried solution https://forum.qt.io/topic/47495/upload-ios-image-with-qt/11 – Deepak Patel Mar 02 '18 at 09:13
  • Android Studio doesn't seem to have the "New > Assets Folder" option anymore. Updated the answer to include the proper file path. Note that `assets` is parallel to `res` folder-structure wise. – sunadorer Apr 18 '18 at 06:49
29

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());
Ajesh
  • 291
  • 3
  • 2
6

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)

Alex Cohn
  • 56,089
  • 9
  • 113
  • 307
Khai Nguyen
  • 3,065
  • 1
  • 31
  • 24
1

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");
Jimale Abdi
  • 2,574
  • 5
  • 26
  • 33
1

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

Clean Coder
  • 496
  • 5
  • 12
0

From the official guide https://developer.android.com/develop/ui/views/layout/webapps/load-local-content :

  1. Store the HTML as an asset in app/src/main/assets/
  2. Use WebViewAssetLoader to load the asset. Construct it in your onCreate() as follows:
final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
         .addPathHandler("/assets/", new WebViewAssetLoader.AssetsPathHandler(this))
         .addPathHandler("/res/", new WebViewAssetLoader.ResourcesPathHandler(this))
         .build();
  1. Subclass WebViewClient to wrap WebViewAssetLoader:
private static class LocalContentWebViewClient extends WebViewClientCompat {

    private final WebViewAssetLoader mAssetLoader;

    LocalContentWebViewClient(WebViewAssetLoader assetLoader) {
        mAssetLoader = assetLoader;
    }

    @Override
    @RequiresApi(21)
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     WebResourceRequest request) {
        return mAssetLoader.shouldInterceptRequest(request.getUrl());
    }

    @Override
    @SuppressWarnings("deprecation") // to support API < 21
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     String url) {
        return mAssetLoader.shouldInterceptRequest(Uri.parse(url));
    }
}

This basically passes the request URL to WebViewAssetLoader to load web content from an asset.

  1. Use assetLoader from (2) to construct WebViewClient from (3), and set it in your WebView. Your index.html can be loaded by using https and the default domain appassets.androidplatform.net:
mWebView.setWebViewClient(new LocalContentWebViewClient(assetLoader));
mWebView.loadUrl("https://appassets.androidplatform.net/assets/index.html");

Note that loading local files using web-like URLs instead of file:// is desirable as it is compatible with the Same-Origin policy.

dejvuth
  • 6,986
  • 3
  • 33
  • 36