Load local html resource on Android

Local html and sources are necessary when you try to show an error page dealing with situation such as 404, 500 error happened on remote server.

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

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

And make use the image, font resources are avaiable locally!, otherwise it won’t load the webpage

Load in the webview:

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

android_asset is the path for assets.

└── html
├── fonts
·· ├── MuseoSans500.tff.ttf
·· ├── MuseoSans500.woff
·· ├── MuseoSans500.woff2
·· ├── glyphicons-halflings-regular.eot
·· ├── glyphicons-halflings-regular.svg
·· ├── glyphicons-halflings-regular.ttf
·· └── glyphicons-halflings-regular.woff
└── mol_error.html

Reference

Load local html resource on Android

Buy me a coffeeBuy me a coffee

About: arkilis


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.