Monday, October 16, 2017

Android: WebView Load Webpages from URL And Assets



Objective: 
The objective of this Android tutorial is to use Webview and load Webpages from URL and Assets. Refer the screen shots below.

Screenshots:
Part 1: Opening an online website (like google.com)
1. Home page to load the WebView URL http://www.google.com


2. Search for any keyword (like gmail) in Google, which displays the search results as follows:


Part 2: Opening a custom website (html) from local assets folder
1. Let’s imagine we have local html files and images under \src\main\assets folder of the project


2. Index.html will display the image one.jpg file and has hyperlink  (here) to index2.html.


3. On-click of the hyperlink “here” in index1.html, it will take you to index2.html, as shown below

4. Now if you want to open it in mobile, you will see the following output:

5. On-click of “here”, it will open the index2.html, as shown below.


6. On-click of Back button , it will bring it back to previous page. On-click of Back button again, it will close the application.

Instructions to setup:
1. Git clone the project and you should see the project \5_Seekbar_N_Progressbar downloaded.
2. Now open the project in Android Studio
3. Press the keyboard – Shift + F10 to run the App, select the configured virtual device and click OK.

4. You can now see the output in the Android Emulator.

Source Code Explanation:
1. Activity_main.xml ((under \src\res\layout\):
1. Overall Layout is set as "RelativeLayout"
2. Set the Webview component with:
id as "webView"
layout_width as “match_parent”

2. MainActivity.java:
1. Instantiate WebView by using findViewById() by passing their respective id’s as defined in activity_main.xml
2. Set the localURL to point to index.html under assets folder using file:///(i.e  file:///android_asset/index.html).
3. Load the URL using webView.loadURL() function, enable the Javascript (setJavascriptEnabled(true).
4. Set the WebViewClient to instance of new WebViewClient() as shown in the code below.
5. The above logic will load the index.html file.
6. Just incase, if you want to load the google.com, just uncomment webView.loadURL(“http://www.google.com”) and comment out the localURL call.
webView.loadUrl("http://www.google.com");
//webView.loadUrl(localURL);


webView.loadUrl("http://www.google.com");
//webView.loadUrl(localURL);

3. strings.xml (under \src\res\values\)
All string values defined


4. colors.xml (under \src\res\values\):
Default standard colors defined


5. styles.xml (under \src\res\values\)
All the default styles defined.


6. AndroidManifest.xml (under \src\main):
Just add additional line highlighted in yellow to enable the permission to enable Internet.


7. index.html (under src\main\assets\)
“here” having hyperlink (a href) to index2.html.


8. index2.html (under src\main\assets\):


No comments:

Post a Comment