Android WebView code to load local HTML file
I have already discuss on CodeSpeedy how to build an android app which loads a website or web page within the android app using the inbuilt android WebView class. You already may know that you just have to put URL inside loadUrl() and you will be able to load that web page from your android app.
Now suppose you need to load a local HTML page or an offline HTML file within the WebView. So what you have to do? Now I am going to give you the process to load a local HTML file within your android app using the WebView class. It is really going to be very easy. Let’s go forward:
Use android WebView class to load local HTML file or offline HTML page
Here we go. Just remember the loadUrl() where I show you how to load this website:
mWebView.loadUrl("http://170.187.134.184");
It will load our website within android app. Now what to do for offline or local HTML file so that it will also load inside the android app. Well, to do it first you need to create a new android resource directory and name it assets inside app folder just like shown below:
Well you can attach CSS, JavaScript and all that you need for a HTML template. That means you can put the complete HTML template inside this directory. Now to load it within WebView you need to use the code given below:
myWebView.loadUrl("file:///android_asset/sample.html");
All the other code will be remain same. To see the full code of main Java and layout file I referrer you to this post – Convert HTML Template Into Android App – Android Studio
That’s it! You have done. Now test your app and have fun.
This is very much useful way to show local html file in android webview.
Thanks for sharing this awesome method to load local html file in android webview.
in sample.html how to link to about.html ?