Loading html file to webview on android from assets folder using Android Studio

前端 未结 3 1530
走了就别回头了
走了就别回头了 2020-12-01 09:34

I\'m using Android Studio/Gradle.

app\\src\\main\\android_asset folder has the file called chart.html..

I\'m trying to load this file to my webview like this

3条回答
  •  温柔的废话
    2020-12-01 09:54

    Similar problem :

    I use many productFlavors with different applicationId.

    If I attempt to load a html file from res/raw/file.html I get a ClassNotFoundException Didn't find class "product.flavor.package.R$raw"

    The R.java file has a different Package name.

    It look's like you can't load a URL from file like : webView.loadUrl( "file:///android_res/raw/page.html"); because the WebView try to use the R.class file with has a different package name.

    I assume the ERR_FILE_NOT_FOUND from loading a html file from assets has the same problem but you don't see the exception. ( webView.loadUrl( "file:///android_assets/page.html" ); )

    With this small work around I solve my problem :

    try {
            AssetManager assetManager = context.getAssets();
            InputStream stream = assetManager.open("page.html");
            BufferedReader r = new BufferedReader(new InputStreamReader(stream));
            StringBuilder total = new StringBuilder();
            String line;
            while ((line = r.readLine()) != null) {
                total.append(line).append("\n");
            }
            webView.loadDataWithBaseURL(null, total.toString(), "text/html", "UTF-8", null);
        } catch (Exception xxx) {
            Log.e(TAG, "Load assets/page.html", xxx);
        }
    

    I hope this helps. Stephan

提交回复
热议问题