Coding for a WebView in Android

In the previous section, we create an assets folder to hold all our web pages. What we'd like to do now is to set up an array to hold all the html pages. We can then access each webpage with something like pages[position], where position is the position of each item in the grid.

We could set up the array like this:

String[ ] pages;

pages[0] = "cat.html";
pages[1] = "dog.html";

However, our web pages are in the assets folder. You have to access the assets folder like this:


So you need the word file followed by a colon and then three forward slashes. You then type android_asset. (Note the singular for asset: it's not assets.) After another forward slash, you type the name of your file. So we could set up our pages array this way:

String[ ] pages;

pages[0] = "file:///android_asset/cat.html";
pages[1] = "file:///android_asset/dog.html";

Instead, we'll set up an array like we did previously - from a string array XML file.

Right-click your res > values folder in the Explorer area to the left of Android Studio. From the menu that appears, select New > Values resource file. In the dialogue box, type pages_array as the File name:

The New Resource FIle dialogue box

Click OK to create a new XML file:

<?xml version="1.0" encoding="utf-8"?>

In between the two resource tags, type <string-array name="web_pages">. Hit the enter key on your keyboard to complete the tag:

<?xml version="1.0" encoding="utf-8"?>

<string-array name="web_pages">



In between the two string-array tags, type the first of the array items:


Your XML file should look like this:

An item tag added to an XML string array

Now add the rest of the items for the array


You can copy and paste here, as the only thing you need to change is the name of the HTML page: dog, fish, horse, etc. Your XML file should look like this:

A string array set up in an Android XML file

You can close this file now, as we're done with it.

Go back to your file. Set up another string array at the top of the code, just below the labels one:

String[ ] labels;

String[ ] pages;

In the onCreate method, we can assign our array from the XML file to the pages array. Add this line just below the one that sets up the labels array:

Resources res = getResources();
labels = res.getStringArray(R.array.headings);

pages = res.getStringArray( R.array.web_pages );

Your code should look like this in earlier versions of Android Studio (the two new lines are highlighted):

Java code to set up an array pulled from an Android XML file

And this in later versions:

Java code to set up an array pulled from an XML file in Android Studio 3

You don't have to create string arrays in XML file, but they do stop your code from being cluttered with array code.

We now need to set up an onItemClickListener. This, as its name suggests, listens out for clicks or taps on the items in your grid.

Add this code to your onCreate method, just after grid.setAdapter:

grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {



The lines are quite lengthy, so it might be easier to copy and paste it from this page. (You might need to delete some spaces that come from copying HTML from this page. See the code in the image below to see how it should look.) Don't forget the three symbols on the last line: a curly bracket, a round bracket and a semicolon.

You might get red text for AdapterView and View. If so, press ALT + ENTER to add the libraries. Or type import android.widget.AdapterView; and import android.view.View; at the top of your code

The only thing we really need from the listener is the position variable in the onItemClick method. This will tell us which grid item was clicked: grid item 0, grid item 1, grid item 2, etc. We can use the numbers to grab a page from our pages array.

Add these three lines between the curly brackets of the onItemClick method:

Intent webPageIntent = new Intent(getApplicationContext(), DisplayPage.class);

webPageIntent.putExtra("WEB_PAGE", pages[ position ] );

startActivity( webPageIntent );

You've met this code before. All we're doing is setting up an Intent to start a new Activity. We're also using putExtra to send the name of the webpage to the new Activity. The key name we've come up with is WEB_PAGE (you can change this, if you want); the value for the key is pages[ position ]. This will send something like file:///android_asset/cat.html or file:///android_asset/dog.html to the new Activity.

You'll have some red text, though. Click inside of Intent and press ALT + ENTER to add the library. Or type import android.content.Intent; at the top of the code. It should look like this in earlier Android Studio versions:

Java code to recognise clicks on a GridView item

And this in later ones:

Java code to recognise clicks on a GridView item in Android Studio 3

However, you'll still have red text for DisplayPage. This is the new Activity. Because we haven't created this Activity yet, you'll get an error for it. Let's create the Activity now.


Add a new Activity

Right click on your java folder (it's probably underlined in red because of the error.) From the menu that appears, select New > Activity > Empty Activity. In the Activity Name box, type DisplayPage:

New Activity dialogue box

Make sure that Backwards Compatibility (AppCompat) is selected, and click Finish. When the Activity is created, the red text from the new Intent line should be gone. It's gone because you now have a class file called DisplayPage.

As well as the class file called DisplayPage, an XML file with the name activity_display_page was created. Load up this file, if it's not already displayed. (It's in the res > layout folder).

In Design view, locate the WebView control, which is in the Containers section of the Palette in earlier versions of Android Studio:

The WebView widget in the Android Studio palette

In later versions, they've moved the WebView to the Widgets section:

The WebView widget in the Android Studio 3 palette

Drag a WebView onto your blank layout. It should look like this:

A WebView on an Android layout

Add some constraints by clicking the yellow plus symbol in the layout toolbar (Infer Constraints). This will bind the WebView to the sides of the screen. In the Properties or Attributes area to the right, change the ID to webPageView:

Properties of a WebView

Attributes of a WebView

And that's all we need for the layout of the WebView. We can turn to the code behind the layout.


WebView Code

Load up your file to get at the code.

Just like we did before, we can set up an Intent object, and then get that extra information we sent in the file. This, if you recall, was the name of a web page in our assets folder. Add these two lines in the onCreate method of DisplayPage:

Intent page = getIntent();

String myPage = page.getStringExtra("WEB_PAGE");

The webpage will end up inside of the String variable that we've called myPage.

Next, we can get a reference to the WebView on the XML page.

WebView myWebView = (WebView) findViewById( );

You may need to ALT + ENTER any red text. Or add these to the top of your code:

import android.content.Intent;
import android.webkit.WebView;

The next line we need is this one:

myWebView.setWebViewClient( new WebViewClient( ) );

If we didn't have this line then Android would try to launch a browser to locate our page. By setting myWebView to be the WebClientView, we can prevent this and make sure it loads a local page.

(ALT + ENTER for WebViewClient. Or add import android.webkit.WebViewClient; at the top of your code.)

Finaly, add this line:

myWebView.loadUrl( myPage );

The method called load does what you expect it to do: loads a web page that is between its round brackets. For us, this was the webpage stored in the variable myPage. You can, however, type a real web address here:

myWebView.loadUrl( "" );

If you're accessing the internet, you need to set a permission in the Android Manifest file. Double click this file to open it. Type the following somewhere near the top, just before the application tags:

<uses-permission android:name=" " />

As soon as you type the left angle bracket, you'll see a popup. Select uses-permission and Android Studio will fill the rest of it in for you. You'll also see a long list of permissions you can choose from:

A list of Android permissions

Select the INTERNET one, if you want to request a web page from the internet.

However, our web pages are coming locally, so we don't need to add this.

The only thing left to do is add the UP arrow in your App Bar at the top, the one that takes you to the main screen. We've done this before a few times, so won't explain it here. Just replace this line in your Manifest file:

<activity android:name=".DisplayPage"></activity>

with this:

<activity android:name=".DisplayPage" android:parentActivityName="MainActivity" >


android:value="MainActivity" />


You can run your app now. You should be able to tap on a grid item. When you do, you'll be taken to the second Activity, the one with the WebView. Inside the WebView, you should see a web page appear.

In the next lesson below, you'll see how to set API levels for your projects.

Back to the Android Contents Page