Byron Kiourtzoglou

About Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Android WebView Example

In Android, you can use the WebView component in order to present markup pages from URL or custom html markup page (short of like a browser, but in your own application…). In this tutorial we are going to create an use two Activities. The main Activity will contain a button. When the user presses that button, another activity launches which will contain a web view and will present the Home Page of JavaCodeGeeks.

For this tutorial, we will use the following tools in a Windows 64-bit platform:

  1. JDK 1.7
  2. Eclipse 4.2 Juno
  3. Android SKD 4.2

1. Create a new Android Project

Open Eclipse IDE and go to File -> New -> Project -> Android -> Android Application Project and click Next.

You have to specify the Application Name, the Project Name and the Package name in the appropriate text fields and then click Next.

In the next window make sure the “Create activity” option is selected in order to create a new activity for your project, and click Next. This is optional as you can create a new activity after creating the project, but you can do it all in one step.

Select “BlankActivity” and click Next.

You will be asked to specify some information about the new activity.  In the Layout Name text field you have to specify the name of the file that will contain the layout description of your app. In our case the file res/layout/main.xml will be created. Then, click Finish.

2. Create the Layout of the main Activity

Open res/layout/main.xml file :

And paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/buttonUrl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="JavaCodeGeeks Home Page" />

</LinearLayout>

Now you may open the Graphical layout editor to preview the User Interface you created:

3. Create a new Activity

Go to the Package Explorer and right click on the package (in our case com.javacodegeeks.android.androidwebviewexample). Select New -> Class. Put the appropriate attributes as shown in the picture below:

As you will see a new java file has been created:

4. Create the Layout of the new activity

To create a new layout file, go to the Package Explorer and right click on the res/layout folder. Select New -> Other -> Android -> Android XML Layout File. And click Next:

Then specify the name of the file and the Layout type and click Finish:

As you will see in the Package Explorer the new /res/layout/webcontent.xml file has been created:

Open that file and paste the following code:

<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

5. Code

Open WebActivity.java and paste the following code:

package com.javacodegeeks.android.androidwebviewexample;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class WebActivity extends Activity {

	private WebView webView;

	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.webcontent);

		webView = (WebView) findViewById(R.id.webView);

		webView.getSettings().setJavaScriptEnabled(true);

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

		//String customHtml = "<html><body><h2>Greetings from JavaCodeGeeks</h2></body></html>";
		//webView.loadData(customHtml, "text/html", "UTF-8");

	}

}

Open MainActivity.javaand paste the following code:

package com.javacodegeeks.android.androidwebviewexample;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

	private Button button;

	public void onCreate(Bundle savedInstanceState) {
		final Context context = this;

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		button = (Button) findViewById(R.id.buttonUrl);

		button.setOnClickListener(new OnClickListener() {

		  @Override
		  public void onClick(View arg0) {
		    Intent intent = new Intent(context, WebActivity.class);
		    startActivity(intent);
		  }

		});
	}
}

6. Edit AndroidManifest.xml

When you want to display Internet content in your Application you need to set the appropriate permissions in your AndroidManifest.xml. You can do this by adding the followint line in AndroidManifest.xml:

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

We also need to declare our new Activity. So, open AndroidManifest.xml:

And paste the following code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.javacodegeeks.android.androidwebviewexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".WebActivity"
            android:theme="@android:style/Theme.NoTitleBar" />

        <activity
            android:name="com.javacodegeeks.android.androidwebviewexample.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

7. Run the application

This is the main screen of our Application:

Now, when you press the button:

8. Load custom markup

Open WebActivity.java and un-comment the last two lines:

package com.javacodegeeks.android.androidwebviewexample;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class WebActivity extends Activity {

	private WebView webView;

	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.webcontent);

		webView = (WebView) findViewById(R.id.webView);

		webView.getSettings().setJavaScriptEnabled(true);

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

		String customHtml = "<html><body><h2>Greetings from JavaCodeGeeks</h2></body></html>";
		webView.loadData(customHtml, "text/html", "UTF-8");

	}

}

9. Run the application

Now, when you press the button on the main sceen:

Download Eclipse Project

This was an Android WebView Example. Download the Eclipse Project of this tutorial: AndroidWebViewExample.zip

Related Whitepaper:

Beginning Android Application Development (Free Sample Chapter)

Create must-have applications for the latest Android OS!

The Android OS is a popular and flexible platform for many of today's most in-demand mobile devices. This full-color guide offers you a hands-on introduction to creating Android applications for the latest mobile devices. Veteran author Wei Meng Lee accompanies each lesson with real-world examples to drive home the content he covers. Beginning with an overview of core Android features and tools, he moves at a steady pace while teaching everything you need to know to successfully develop your own Android applications.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books