WebView

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

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button