Android WebView example

Android’s WebView allows you to open an own windows for viewing URL or custom html markup page.

In this tutorial, you will create two pages, a page with a single button, when you clicked on it, it will navigate to another page and display URL “google.com” in WebView component.

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. Android Layout Files

Create two Android layout files – “res/layout/main.xml” and “res/layout/webview.xml“.

File : res/layout/main.xml


<?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="Go to http://www.google.com" />
            
</LinearLayout>

File : res/layout/main.xml – WebView example


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

2. Activity

Two activity classes, an activity to display a button, another activity display the WebView with predefined URL.

File : MainActivity.java


package com.mkyong.android;

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, WebViewActivity.class);
		    startActivity(intent);
		  }

		});

	}

}

File : WebViewActivity.java


package com.mkyong.android;

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

public class WebViewActivity extends Activity {

	private WebView webView;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview);

		webView = (WebView) findViewById(R.id.webView1);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.loadUrl("http://www.google.com");

	}

}

3. Android Manifest

WebView required INTERNET permission, add below into AndroidManifest.xml.


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

File : AndroidManifest.xml – See full example.


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

    <uses-sdk android:minSdkVersion="10" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".WebViewActivity"
            android:theme="@android:style/Theme.NoTitleBar" />
        
        <activity
            android:label="@string/app_name"
            android:name=".MainActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

4. Demo

By default, just display a button.

android webview example

Click on button, WebView is display.

android webview example

5. Demo, Again

WebView allow you to manually load custom HTML markup, via webView.loadData(), see modified version :


package com.mkyong.android;

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

public class WebViewActivity extends Activity {

	private WebView webView;

	public void onCreate(Bundle savedInstanceState) {
	   super.onCreate(savedInstanceState);
	   setContentView(R.layout.webview);

	   webView = (WebView) findViewById(R.id.webView1);
	   webView.getSettings().setJavaScriptEnabled(true);
	   //webView.loadUrl("http://www.google.com");

	   String customHtml = "<html><body><h1>Hello, WebView</h1></body></html>";
	   webView.loadData(customHtml, "text/html", "UTF-8");

	}

}

Now, when button is clicked, a custom html page is displayed.

android webview example

Download Source Code

Download it – Android-WebView-Example.zip (16 KB)

References

  1. Official Android webView example
  2. Android WebView Javadoc
  3. Switching Android activity
author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
newest oldest most voted
Mukesh Yadav
Guest
Mukesh Yadav

Hello sir

ThAnkyou for this tutorial,

I have a question-
Main actvity XML file have 2 buttons frist btn click then open browser activity and show web page I m set a url in browser activity .But
How to set second button to load diffrent url in same browsers activity
Plz sir reply

Waiting for your reply

Thank you

Vera
Guest
Vera

This is an amazing tutorial. But what if I want to use Javascript to make the application more interactive ?? I tried form developers site..but they only gave it to flip the images…when I tried with buttons and text boxes..it never worked for me 🙁

Please help !! thanks in advance !!

Vera

Cong Hoan
Guest
Cong Hoan

you can trying with phonegap

footiepal
Guest
footiepal

hello. i have a website, with some live wallpaper apk’s. so i created app with webview on my site, but when i tryng to download an apk, looks like its nothing happening. so how do i enable direct download on webview. code looks like this: import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.webkit.WebView; import android.webkit.WebViewClient; public class FootiepalActivity extends Activity { private WebView mWebView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mWebView = (WebView) findViewById(R.id.webview); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setLoadWithOverviewMode(true); mWebView.getSettings().setUseWideViewPort(true); mWebView.getSettings().setPluginsEnabled(true); mWebView.loadUrl(“http://www.exemple.com”); mWebView.setWebViewClient(new HelloWebViewClient()); } private class HelloWebViewClient extends WebViewClient { @Override… Read more »

Jae
Guest
Jae

Please comment if the following program works or not. This is about to create an icon, then after clicking on the icon will bring to another html page. That html page will bring to other html pages. package com.xxxxx.xxxxx.xxxx; import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.webkit.WebView; import android.widget.Button; import android.view.View; import android.content.Intent; import android.view.View.onClickListener; public class UTActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void startActivity() { Intent launchActivity = new Intent (this, UTActivity.class); launchActivity).loadUrl(“file:///xxxxxxxxx.html”); } Button button = (Button) findViewById(R.id.trigger); button.setOnClickListener(new View.onClickListener() {… Read more »

Narita
Guest
Narita

I tried the example but I am getting blank screen on clicking the button. Log has the following content – 07-05 10:24:03.924: W/webcore(1224): java.lang.Throwable: EventHub.removeMessages(int what = 107) is not supported before the WebViewCore is set up. 07-05 10:24:03.924: W/webcore(1224): at android.webkit.WebViewCore$EventHub.removeMessages(WebViewCore.java:1683) 07-05 10:24:03.924: W/webcore(1224): at android.webkit.WebViewCore$EventHub.access$7900(WebViewCore.java:926) 07-05 10:24:03.924: W/webcore(1224): at android.webkit.WebViewCore.removeMessages(WebViewCore.java:1795) 07-05 10:24:03.924: W/webcore(1224): at android.webkit.WebView.sendOurVisibleRect(WebView.java:2917) 07-05 10:24:03.924: W/webcore(1224): at android.webkit.ZoomManager.setZoomScale(ZoomManager.java:593) 07-05 10:24:03.924: W/webcore(1224): at android.webkit.ZoomManager.access$1700(ZoomManager.java:49) 07-05 10:24:03.924: W/webcore(1224): at android.webkit.ZoomManager$PostScale.run(ZoomManager.java:984) 07-05 10:24:03.924: W/webcore(1224): at android.os.Handler.handleCallback(Handler.java:605) 07-05 10:24:03.924: W/webcore(1224): at android.os.Handler.dispatchMessage(Handler.java:92) 07-05 10:24:03.924: W/webcore(1224): at android.os.Looper.loop(Looper.java:137) 07-05 10:24:03.924: W/webcore(1224): at android.app.ActivityThread.main(ActivityThread.java:4424) 07-05 10:24:03.924: W/webcore(1224): at java.lang.reflect.Method.invokeNative(Native Method) 07-05 10:24:03.924:… Read more »

Narita
Guest
Narita

I am getting this error as well
07-05 17:20:30.623: E/chromium(1243): external/chromium/net/disk_cache/backend_impl.cc:2022: [0705/172030:ERROR:backend_impl.cc(2022)] Corrupt Index file

Meena
Guest
Meena

Hi ,
I am very new to Android , i created the program and in first activity it showing me as Connect the link , later in second activity it telling me to force down the emulator . My doubt is , how should i check Internet and Connection of Internet in ANDROID ? Please anyone help me ??

Meena
Guest
Meena

Hi all ,
My First Activity works well , but in second activity while i click Connect button, it is showing me as Force to Shut down .. Same code i worked . Wats the problem . Can you temme pls?

Gajendra Jore
Guest
Gajendra Jore

Great job….

Sandeep Reddy
Guest
Sandeep Reddy

WebView.java package org.example.webviewdemo; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; public class WebViewDemo extends Activity { private WebView webView; private EditText urlField; private Button goButton; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Create reference to UI elements webView = (WebView) findViewById(R.id.webview_compontent); urlField = (EditText)findViewById(R.id.url); goButton = (Button)findViewById(R.id.go_button); // workaround so that the default browser doesn't take over webView.setWebViewClient(new MyWebViewClient()); // Setup click listener goButton.setOnClickListener( new OnClickListener() { public void onClick(View view) { openURL(); } }); //… Read more »

Udhay
Guest
Udhay

How to set the captured image in Android phone as wallpaper programatically??
Take a look at this post:
http://android.programmerguru.com/simple-camera-activity/

betula
Guest
betula

can i return first application with “back” button in the second application? If I can, how?

BuscoColegio
Guest
BuscoColegio

So you could set up an html form in a WebView but how do you collect user responses in your Android code? it exists anything similar to request.getParameter() in Android?

thanks!!

sultan
Guest
sultan

sir
please, tell me how to i use hyperlink ….by which i can connect with from list view to webview. (for read pdf material)

Honey Hong
Guest
Honey Hong

Thanks for the WebView tutorial too. I managed to solve 2 things in a day because of your tutorials. 🙂

ThePCWizard
Guest
ThePCWizard

thanks, I was looking for that second method.

roy
Guest
roy

Hi am getting this error when i am launch the webview from listview activity. See interesting thing is when i am try to launch webview two or three time it’s work fine. After am getting this error. Please give me perfect solution . All ideas are welcome 10-30 18:53:06.966: W/webcore(20239): java.lang.Throwable: EventHub.removeMessages(int what = 107) is not supported before the WebViewCore is set up. 10-30 18:53:06.966: W/webcore(20239): at android.webkit.WebViewCore$EventHub.removeMessages(WebViewCore.java:1671) 10-30 18:53:06.966: W/webcore(20239): at android.webkit.WebViewCore$EventHub.access$7800(WebViewCore.java:920) 10-30 18:53:06.966: W/webcore(20239): at android.webkit.WebViewCore.removeMessages(WebViewCore.java:1783) 10-30 18:53:06.966: W/webcore(20239): at android.webkit.WebView.sendOurVisibleRect(WebView.java:2858) 10-30 18:53:06.966: W/webcore(20239): at android.webkit.ZoomManager.setZoomScale(ZoomManager.java:586) 10-30 18:53:06.966: W/webcore(20239): at android.webkit.ZoomManager.access$1700(ZoomManager.java:49) 10-30 18:53:06.966: W/webcore(20239): at android.webkit.ZoomManager$PostScale.run(ZoomManager.java:977) 10-30… Read more »

trackback
Android Web Browser : Android Community - For Application Development

[…] If you are looking to make your own browser using a webView then check this tutorial. […]

trackback
setting autolink property : Android Community - For Application Development

[…] can get an idea from here with a Simple Example of How to Handle a WebView.The Link is as follows:-WebView Example. I hope this helps you a […]

Carlos Andres Becerra
Guest
Carlos Andres Becerra

Hi. Excelent example, many thanks, now one question… Im have a webpage and like the application load my Webpage, then modidy the url in webView.loadUrl(“”); and load fine. Now the problem is when make click in any link of the my Web because my application launch the Navigator and not open the webpage into my app. How can make this? Load only in my app my Webpage? Thanks for your help

sadiq awosanmi
Guest
sadiq awosanmi

you need to override the default application that handles URLs. you can do this by adding this 2 lines to your WebViewActivity.java class.

WebView myWebView = (WebView) findViewById(R.id.webView1);
myWebView.setWebViewClient(new WebViewClient());
wojt
Guest
wojt

Very useful is this Your tutorial. Thank you. And maybe You know a way to webChromeClient?

linkinstreet
Guest
linkinstreet

Kinda new with Android, but was wondering how do I skip the “press button to go to app” and just directly go to WebView function. Thank you

asimnet
Guest
asimnet

yaa
how is that ?

trackback
webview and android eclipse : Android Community - For Application Development

[…] Android WebView Example […]

Neha
Guest
Neha

Hi,

I want to draw something on WebView. How can i acheive that? Please help

Lester
Guest
Lester

Hi,
A bit cheeky this one 🙂 – please could you provide me with code (and its location – filename) that I can use to launch a url. I have created the graphics – just need to launch the url when icon selected.

Many thanks

Lester

krunal
Guest
krunal

Hi i have html form with input type=”radio” but cant view it in webview
other things are visible of table

Saurav
Guest
Saurav

Hey! i’ve downloaded your project & tried it onto Eclipse. There is a problem, when i click

 Go to http://www.google.com"  

it starts the default Android Browser… Please help me out!!

AbdulWajid
Guest
AbdulWajid

webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
// this is set webview in ur activity
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(“http://www.google.com”);

abhi
Guest
abhi

i ve downloaded ur code & run it but it displays only second screenshot posted above not d first wer it displays google.com homepagwhat to do..???
plz help

trackback
How to fix a webview error in android? - How-To Video

[…] create a simple Android application that is just a webview. I’ve been following a tutorial (www.mkyong.com/android/android…) but have adapted it to have just a webview instead of a button that opens a […]

trackback
How to fix a webview error in android? : Android Community - For Application Development

[…] create a simple Android application that is just a webview. I’ve been following a tutorial (http://www.mkyong.com/android/android-webview-example/) but have adapted it to have just a webview instead of a button that opens a […]

trackback
How to fix a webview error in android? | BlogoSfera

[…] create a simple Android application that is just a webview. I’ve been following a tutorial (http://www.mkyong.com/android/android-webview-example/) but have adapted it to have just a webview instead of a button that opens a […]

Abhijeet
Guest
Abhijeet

String customHtml = ” window.print() Menu Order “;

if want to print the output to the local printer how can i do it.. window.print() java script function doesn’t work..
plz help me out with source code