Load local html resource on Android using webView

Local html and sources are necessary when you try to show an error page dealing with situations such as 404, 500 and etc errors happened on remote server. And here is how:

First, create a new class named MyWebViewClient:

package apeapp.webviewclient.testwebviewclient;

import android.os.Build;
import android.util.Log;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

class MyWebViewClient extends WebViewClient {

    final String TAG = "HTTPERROR";

    @Override
    public void onReceivedHttpError(
            WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
        super.onReceivedHttpError(view, request, errorResponse);

        int statusCode = 0;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            statusCode = errorResponse.getStatusCode();
        }
        if (400 == statusCode || 404 == statusCode || 500 == statusCode) {
            view.loadUrl("file:///android_asset/test.html");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Log.e(TAG, errorResponse.getReasonPhrase());
        }
    }
}

Then in the WebView:

package apeapp.webviewclient.testwebviewclient;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        WebView myWebView = (WebView) findViewById(R.id.webview);
        myWebView.setWebViewClient(new MyWebViewClient());
        myWebView.loadUrl("https://www.example.com");
    }
}

But be careful! Put your resources under the assets, for example:

/Users/ben/ben_ws/android_dev/your-Mobile-Android/app/src/main/assets/html

Now in the webview:

view.loadUrl("file:///android_asset/html/mol_error.html");

Thanks for reading.

comments powered by Disqus