Tutorial Details
- Difficulty: Beginner
- Technology: Android SDK
- Completion Time: 10 - 15 Minutes
This quick tip will demonstrate how you can embed an Android WebView in your application with the the WebKit engine. You will learn how to both load an external URL and render custom markup that you supply in-app.
Step 1: Preparation
Start off by creating a new Android SDK project in your IDE of choice. You can name the main activity, package root and project anything you want. Choose Android 1.6 as your platform to maintain broad compatibility.
Step 2: Setting up the WebView Widget
The WebView widget works just like any other Android SDK widget: you declare it in a layout file and can then access it from an Activity and tell it what to do.
Open your main.xml layout file or create it if your IDE didn’t already do so. Next, declare the WebView widget as a child of the LinearLayout element, making sure to specify an ID so you can access the widget later. As always, don’t forget to declare the width and height or else your app will throw an exception. For demonstration purposes, we’re going to have the component fill up the whole screen by setting the android:layout_width and android:layout_height attributes to fill_parent.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<WebView android:id="@+id/web_engine"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
Step 3: Requesting Internet Permission from the Android Manifest
Since we’re going to load a URL in the WebView widget, we have to make sure to request permission to access the Internet in AndroidManifest.xml
Open it up and declare a uses-permission element where you specify android.permission.INTERNET as the android:name attribute, like so (line 6):
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.webkitdemo">
<uses-permission android:name="android.permission.INTERNET" />
<application android:icon="@drawable/icon" android:label="WebKitDemo">
<activity android:name=".WebKitDemo">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
If you start your application in the Android emulator now, you will see a blank, white screen. Why? Well, we haven’t told WebView to render anything yet – that’s what we’ll do next.
Step 4: Load a Web Page
Open up your main activity (com.webkitdemo.WebKitDemo in our case) and add the following code into the onCreate() method:
WebView engine = (WebView) findViewById(R.id.web_engine);
engine.loadUrl("http://mobile.tutsplus.com");
This snippet of code accesses the WebView widget via its resource ID and invokes loadUrl(). Start the app in the emulator and view the result: it should display the site you’re currently on!

Step 5: Render Custom Markup
Next, we’re going to replace the loadUrl() call with loadData(), which takes three arguments:
- String htmlData
- String mimeType
- String encoding
Comment out the engine.loadUrl() line and insert the following code underneath it:
String data = "<html>" +
"<body><h1>Yay, Mobiletuts+!</h1></body>" +
"</html>";
engine.loadData(data, "text/html", "UTF-8");
Compile and restart the application in the emulator and you should see this:

Technically, you can pass another type of data with its respective mime-type to this method, but most of the time you’ll be using text/html with a UTF-8 encoding. Don’t forget that you’re using WebKit, a powerful web engine; you can use CSS3, JavaScript etc. when you design your manuals or anything you want it to display.
NOTE: One of WebView’s peculiarities is the fact that JavaScript is disabled by default. The reason for this is that in most cases when you’re embedding a WebView into your application, you’re using it for a help manual or something that doesn’t require JavaScript. Nevertheless, it’s easy to enable it if you do need it:
engine.getSettings().setJavaScriptEnabled(true);
Extra features
You may have noticed that the widget doesn’t have a toolbar. This is intended, as you would normally launch the native web browser app if you want navigation capabilities. There is, however, a way to control it programmatically. Try invoking one of the following methods on the instance of your widget:
- reload(): Refreshes and re-renders the page.
- goForward(): Goes one step forward in browser history.
- goBack(): Goes one step back in browser history.
The API has a lot more to offer, but that goes beyond the scope of this Quick Tip.
Conclusion
You should now be familiar with the basic usage of the very useful Android WebView widget. You can use it to display an “about” web page for your application or a user manual – all sorts of stuff. Technically, you can even write your application using JavaScript, CSS and HTML and display it using the widget, although that wouldn’t be too practical… Or would it?

Thanks for the write up. I think this will help open doors for web developers who are comfortable writing html, css, javascript and so on yet are having a time trying to get their head around the android sdk.
Interesting, but can you load a local .html file?
you can do it with webView.loadData(data, mimeType, encoding); method.
engine.loadData(“file:///yourpath.html”,”text/html”, “UTF-8″);
If my html file is placed in res->raw, what should be the value of “yourpath.html” insided
engine.loadData(“file:///yourpath.html”,”text/html”, “UTF-8″);
?
Thanks,
Lalit Bhesdadiya
At Step 4, I must be doing something wrong. I get an error when I do this:
++++++++++++++++++++
package com.WebKitDemo;
import android.app.Activity;
import android.os.Bundle;
public class WebKitDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView engine = (WebView) findViewById(R.id.web_engine);
engine.loadUrl(“http://mobile.tutsplus.com”);
}
}
+++++++++++++++
you should input a line “import android.webkit.WebView;” after “import android.os.Bundle;”.
@ fractalbit: Yes, it certainly is possible.
Basically you're going to invoke the same method, loadData(), and you're going to give it the contents of the local HTML file in form of a String. Place your HTML file in the raw resources directory: ./res/raw (create if it doesn't exist yet). You'll be referencing the file name (minus the extension) in your code later, so name it appropriately. For this example I've named it "test.html".
Place the following code into onCreate() and make sure you've commented out or are replacing any previous calls to loadData().
——————————————-
String data = "";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.test)));
String line;
while ((line = br.readLine()) != null) {
data += line;
}
br.close();
} catch (IOException e) {
e.printStackTrace();
data = "Failed loading web page!";
}
engine.loadData(data, "text/html", "UTF-8");
——————————————————
That snippet of code uses a BufferedReader to read and append the contents of your local HTML file to a String named "data", which is then passed on to engine.loadData() as the first parameter. You're going to have to modify this part, depending on what you named your file:
getResources().openRawResource(R.raw.test)
openRawResource(int resourceID) returns an InputStream, which the BufferedReader is wrapped around. "R.raw.test" points to the resource that will be loaded, so if you named your file "manual.html" then you're going to have to use "R.raw.manual".
Feel free to post another comment if you have any further questions.
==================================
@ Ken: Looks like your IDE didn't automatically take care of importing the class that you're referencing in your code: WebView.
Add this to the top of the file, along with the other imports:
import android.webkit.WebView;
Which IDE are you using?
Hannes,
I have an image inside the html page (which is placed inside res->raw folder). So when trying above solution, I was able to load the html text but NOT the image inside the html page. do I have to do anything special for displaying the image?
Thanks,
Lalit Bhesdadiya.
You do have to do something different. You need to put images into the “assets” folder. If you don’t have one, create it. The “assets” folder should NOT be in the res folder, but beside it.
Once your image is there, you can refer to the image from your html file by using something like:
THEN, you need to render the html a little differently using:
engine.loadDataWithBaseURL(“fake://not/needed”,data, “text/html”, “UTF-8″, “”);
Many Thanks Hannes! That was it.
I am using Eclipse. Didn't know of any others.
Wonder why "import android.webkit.WebView; " was not there in my file. Think I missed something before? I will review.
PS
I am hoping you are German. The Dutch broke my heart today. (I am married to a Brazilian) The only thing worse will be if Argentina advances and/or God forbid, become champions.
GO GERMANY!!
Does anybody know a good way to display a powerpoint presentation in a webview widget? I’ve tried to save the ppt as html, and bringing up the ppt in internet explorer, it works as it should. In the webview, (javascript enabled – so the slide links on the left margin call the correct slide in the presentation) it displaying the slides and links and it calls the slides correctly, but some of the slides have text that wraps to the next line overlapping the line below making some lines unreadable. Thanks in advance for any replies.
What if you wanted to package a site that has multiple pages?
hello .
I can’t get the webpage . My system is behind a proxy. What can i do?
Ive an idea but no talent.
On maybe 2.0 and above, we can launch .swf or flash files from a saved part on the phone/mem card via the browser.
Perhaps an app or widget could be used, combining the browser, a flash lite theme or clock, and the idea above to enable people to use flash lite screens on their phones?
Im new to android and your simple example but im having errors in this part..
WebView webView = (WebView) findViewById(R.id.webView);
id cannot be resolved or is not a field..
what do i need to do?
thanks
Juan,
set the content view before loading data into it. I think this should solve the problem. Like below:
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String data = “”;
try {
BufferedReader br = new BufferedReader()
……….
……………..
…………
}
Lalit.
Hi,
I am loading a website in webview remotely that contains only 1 image per page, (not via res/raw), and wonder how i can add a function to long press on the image to invoke a menu that will have an option to save the image to sd card, similar to what happens on the normal phone browser.
Any help will be much appreciated
thanks
lucy
Hey,
i have downloaded your code and try to use it, but if i open my application (emulator or HTC) the default browser opens and show me my entered website like ‘http://XDVDVD.de’
package com.webkitdemo;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
/**
* @author Hannes Holste
*/
public class WebKitDemo extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView engine = (WebView) findViewById(R.id.web_engine);
engine.loadUrl(“http://XDVDVD.de”);
engine.getSettings().setJavaScriptEnabled(true);
//engine.loadData(data, “text/html”, “UTF-8″);
}
}
What’s the problem?
thanks dave
Hey there, i have noticed the same problem as Dave.
When the webkit has to load a page that is designed for mobile phones, it opens it in a normal browser.
Why?
I’m lost at step 4:
Open up your main activity (com.webkitdemo.WebKitDemo in our case) and add the following code into the onCreate() method:
On what page is that placed in Eclipse?
Thanks!
My android SDK installation is working perfectly, the hello work app is working, etc.
But I can’t get this embed-webview-demo-app to work.
ERRORS:
#1. WebView webView = (WebView) findViewById(R.id.webView);
……………id cannot be resolved or is not a field..
#2. R.id.webView is a (hardcoded) integer, I tried to replace it with that value…
Eclipse says “all ok”, but when the emulator executes the app, it doesn’t
work (app error, app crash)
I downloaded the .ZIP with the source files of this demo app, but for
some reason, Eclipse is not loading it when I copy the files to the
correct directory structure (just like the working hello world app…)
The content displayed in webview is not selectable. Please tell me how to enable text selection in android webkit webview.
Please reply asap…
Thanks..
Although, your tutorial is written for 1.6 but in my computer, it always force close until I choose sdk for 2.2.
How do you rename the app, so that it’s not called “WebKitDemo” on an actual device!? Small thing, but I’m wasting hours trying to figure it out!
Project root
res
values
strings.xml
appnameishere
edit that and your good to go
I’m a beginner programmer. I have tried and tried and tried to get webview to work. I even followed the guide on the Android SDK site for webview and I get the same error.
The problem is this line of code in my com.project.Project
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl(“http://google.com”);
WebView engine = null;
engine.getSettings().setJavaScriptEnabled(true);
I tried putting the code in like you have here but I get an error saying that webview isn’t a type.
Hi All,
thank you for this great tutorial.. Now i understand how to embed WebView using the WebKit engine.
I have a question.
Let say my website has 3 separate parts, using CSS style, and I just want to call one part that is the login part. So assume the first part is login part, second is calendar which i have embedded it using google calendar, and the third part is my profile ( with a picture and short description about the user <- this one will available after the user push their login credential ).
My question is, is it possible to use webkit engine and using the javascript and css, to show certain element only? It is not so-utilize to show all element inside one page, because mobile screen is smaller than pc.
Thank you.
Sincerely,
Iqbal.
Hi all,
thanks for your helpful post related to android webview.
i am having the same requirement like “Render Custom Markup” and i followed the same above but i am unable to load the html data into web View.
I have created an .html file using the same data and tried to open the file in browser it is working fine there. but i don’t know why it is not working in android web view .
Can any one suggest me if any other way is there to render custom markup in web view?
Thanks in advance.
Sathish
Excellent article!
You can load a local html file directly into a WebView without using the .loadData method:
In your assets directory, create a simple html file:
Yay, Mobiletuts+!
and name it “demo.html”
In your OnCreate code, comment out the existing .loadURL method:
//engine.loadUrl(“http://mobile.tutsplus.com”);
and add a new .loadURL method:
engine.loadUrl(“file:///android_asset/demo.html”);
I have no idea why “android_asset/filename.html” works instead of a more traditional filepath – nothing in a quick docs search …
When loading an extrenal (live) website in WebView, links open in Android Browser.
How can I “force” them to open in WebView?
There is a solution on StackOverflow but I can’t seem to implent it to this code:
http://stackoverflow.com/questions/2378800/android-webview-click-opens-default-browser
Thanks in advance!
Hi DWMA,
The stack overflow solution will surely work for your requirements.
What you need to do is , just add an custom WebViewClient to your webView.setWebViewClient(your coustom web veiw client object); by overridding the shouldOverrideUrlLoading() method in your custom webview client.
Thanks,
Sathish.
i have problem i made a app to login facebook in this i am using webview . the problem is when i log in webview stores the log in data . so when i log out in facebook it doesn’t delete the data .so is it possible to storing information abt logion credential .
Probably a simple question but if I want to actually store a file in the Android App and then utilize it from there such as a button graphic, Where it would be best to put it and what would the link to it be assuming the file is
“button1.png”
Where would I put this file
and then I have a img tag that uses it
<img src=’???????/button.png’ width=’200px’ height=’35px’>
so what would the path be
This is my first android App so sorry if this is a basic question but I have tried several places.
I heard it was res/raw but I do not know the path to res/raw if that is indeed correct.
Hi
can anyone tell me method how to read data from web view.
Hi Madhuri,
Which data you want to read from web view ? Can you elaborate your issue, so that the solution may reach your needs.
Thanks,
Sathish.
How to save the bookmarks programmatically in our own browser app
Hi,
I have created android application to get the contact list from android phone. In this i’m using Webview.loadurl() to load the home page(index.htm) like,
webview.getSettings().setJavaScriptEnabled(true); webview.loadUrl(“file:///android_asset/assets/www/index.htm”);
This is working in android emulator and phone, not working in “AcerICONIA TAB A50″
showing an error ” webpage is not available at file:///android_asset/assets/www/index.htm ”
Please help me clear this.
The solution for this, no need to give assets folder in link. like as follows
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl(“file:///android_asset/www/index.htm”);
Hi
I am a new programmer who is developing an android project for my final year at Uni. I have created the project activity and package name, now I want to add a webveiw kit to the application. Can you please tell me how to go about this because I am getting an error if I add another package name with the URL for the webview to the app activity , or an option to move the existing app activity package to the new one I added.
I also added this code inside the app activity and is getting an error for the id or the option to either create field ‘id’ type ‘R’ or create constant’id’ in type ‘R’.
I am truly grateful for you help. Thank you.
The code I made reference to seem to disappear from my first comment. The code I added was
WebView myWebView = (WebView) findViewById(R.id.webview);
Websetting websettings = myWebsetting.getSetting();
websettings.setJavaScripteEnabled(true);
How do I add webView to an existing application considering it already has a project and package name?
Thanks.
Try this,
Clean and Build the project once.
If the project already have any other errors, then R.java page may not be updated.
So please clear the errors first if you have errors.
Hi all, great tuts!!
I try follow it but now my problem is this:
I need to make a very simple web based app that runs in local machine with a little db.
Well, first I have purchased a mobile template from mobileTuts (There are only php pages).
Then I have loaded the index.php as well, but from here i don’t reach any linked page.
it appears a “page not found” message over the screen.
This problem happen only when url is like this:
file:///android_asset/myapps/about.php?pat=stripes&high=green
What’s the trick?
Many thanks in advance.
Ps. sorry for my poor english… and also for my PHP skill!! :)
Hi,
Please check the URL whether you have given as below or not?
webview.loadUrl(“file:///android_asset/assets/index.htm”);
Thank you.
hi,
i wanna add tabs in my app action bar but am not able to do it plz help..
thanks