Android WebView Example

1. Introduction to Android WebView

In the course of this tutorial, we will teach you how to use Android WebView and answer to some of the most common questions on android WebView.

  1. Android WebView is an embedded browser that can render static HTML data or even remote URL. A WebView is an android UI component that displays webpages.
  2. WebView encompasses the functionality of a browser that can be integrated to Android application.
  3. It uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, and perform text searches and more.
  4. Most of the android applications like WordPress, Flipboard, fiddly; Google Reader, etc. do integrate WebView, in order to display certain piece of online contents.

Android WebView use WebKit rendering engine to display web pages. If you see the android underlying platform architecture, the WebKit core resides in library layer, and the source is developed in C/C++. From Android application framework layer, the WebView can connect to WebKit using JNI (Java native Interface).

Android-system-architecture Android-system-architecture

If you are interested in taking a look into the Android platform source code, you may visit the following links
Webkit JNI code

2. Open Link on Android Device Browser

At times, you may require to invoke the device browser, when an external link is clicked from app. For example, in most of the mobile advertising platform, when user click on a banner, it redirect user to the ad publisher website to show more info on specific ad. For such similar requirement, you need to open device browser with a URL.

Following code show how to invoke device browser using Android Intent method.

Uri uri = Uri.parse("");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);

The ACTION_VIEW intent action is used to invoke the application based on the specified data. Here in this example, we are using URL as bundle data so it will invoke the specified url in the application that can take such action, eg. browser.  If you provide the data type as phone number, it will automatically open phone dialer.

3. Android WebView Example

Following section of the tutorial, will drive you with step by step approach to create a simple WebView with different configuration params and load home page.

4. Declare WebView Layout

Like any other UI controls in android, you can include the WebView in your xml layout. Below is my xml layout

<LinearLayout xmlns:android=""
    android:orientation="horizontal" >


5. Load Static Html Data on WebView

Following activity class snippet will show you how to initialize WebView instance and load static Html string onto it. Just call loadData()  It takes html string data, mime-type and encoding param as three parameters.

//Instantiating WebView instance
WebView webView = (WebView) findViewById(;
String customHtml = "<html><body><h1>Hello, WebView</h1>" +
           "<h1>Heading 1</h1><h2>Heading 2</h2><h3>Heading 3</h3>" +
           "<p>This is a sample paragraph.</p>" +
webView.loadData(customHtml, "text/html", "UTF-8");

Output of the above code is
Load Static HTML Data on WebView

6. Load Remote URL on WebView

  1. The default behavior of Android is to open device browser, when links are clicked. But as our WebView should work like a embedded browser, we must override to always open the links in the WebView instead redirecting it to the default browser.
  2. We can do this using android WebViewClient. WebViewClient helps to monitor events in a WebView. We have to override the shouldOverrideUrlLoading() method. This method allows performing your own action when a particular URL is selected. Once we are ready with the WebViewClient, we can set the WebViewClient of your WebView using the setWebViewClient() method.
  3. The WebViewClient class has some other useful methods such as onPageStarted()onPageFinished() and onReceivedError() that helps you to show loading progress of WebView content, or handle error.

Checkout my Android tutorial that explains How to show loading progress in Android WebView.

Now let us go back to our example, and take a look into how our activity class looks like.

public class WebViewActivity extends Activity {
	private WebView webView;	

	protected void onCreate(Bundle savedInstanceState) {
		webView = (WebView) findViewById(;
		webView.setWebViewClient(new MyWebViewClient());
		String url = "";

	private class MyWebViewClient extends WebViewClient {
	    public boolean shouldOverrideUrlLoading(WebView view, String url) {
	        return true;

Output of the above code is here

Load Remote URL on WebView

7. Display HTML Text in TextView

Android TextView is also capable of rendering the HTML text. Checkout my post How to Display HTML in Android TextView.

A blogger, speaker, author, a bit of tech freak and a software developer. He is a thought leader in the fusion of design and mobile technologies.

  • Jovanpreet

    That would be a bad idea if you have buttons in your own app you can use imageview instead of webview and then load images into that imageview. You probably have some fashion in the images url like suppose first image name is “PATHTOIMAGEFOLDER/ABC1.JPG” and second image is ABC2.JPG then you can easily manage with having a pointer to image number and increase or decrease pointer as per button click and update image in imageview. You can also use image library like picaso which will cache images and load images quite faster.

    But still if you want to load image in webview(which is quite slower and stupid idea) you can use webview.loadUrl(“IMAGE URL”) by putting different url in place of image url and using the same concept of pointer discussed above.

  • VIshwanath Hiremath

    How to get the URL of the web page after navigation through hyperlinks in webview

    • Nilanchala Panigrahy

      The shouldOverrideUrlLoading method gives you the url. Checkout the params

      public boolean shouldOverrideUrlLoading(WebView view, String url) {
      return true;

      • VIshwanath Hiremath

        Thanks that helped,
        Actually i am building a Download manger app, now the the app is such that the users copy the URL of the file to be downloaded form the browser and paste in my app .

        So i thought it would be more easy for the user if i make a webview which acts like the browser. It is working properly that i can i browse properly in the webview and i am having a button which returns the download link of the file to be downloaded. Its working fine with —-url—-.jpg, .mp3, mp4 and all but when it comes to pdf files i.e —-url—.pdf or .doc then there is no response onclicking the respective link . As in browsers the pdf file is displayed.

        Is there any way that can me that work i.e display pdf or doc files from their url links??

  • Edney Imme

    how can i accept cookies in Webview?

  • JavaTechig

    Dont understand your question quite well..

  • JavaTechig

    updated with more information.

  • javatechig

    You can override shouldOverrideUrlLoading method on WebViewClient.

    client = new WebViewClient(){
    @Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
    Log.d(“Clicked URL” + url);
    return false;

  • javatechig

    You may have a look into the third party lib code

  • Rzenks Mj

    How can i use strings from one activity(class) to another and open the strings in webview ?

    • javatechig

      Please use intent bundle to pass data between activities.

  • Bil Kimes

    Have you worked with presenting PDF content?
    In iOS (Apple Xcode) you can use the UIWebView to load PDF content but not so in Android. Any recommendations how to best accomplish this?

    • Nilanchala Panigrahy

      For rendering pdf you have to use google api support. below code snippet will help.

      String pdfurl = “”; // your pdf url
      String googleDocsUrl = “”+pdfurl; //url for your webview

      Just append your url to url (as in the above code and load that url in your webview.

  • javatechig

    According to my knowledge u cant. Please check the android developer portal documentation.

  • Alex

    I’ve tested your example… and when I type a URL and click the OPEN button I get Webpage not available. I’ve also tryed with my lan connection and internet connection. … I have permission for internet in tha manifest… but I don’t know why this is not working. Thanks

  • Mahesh G V P

    first of all , thanks for the tutorial,but it only solves half of my problem , what i want to achieve is i have a blog which contains pictures, if i press next button , the next image of the blog should appear on the webview, and if i press back the previous image should appear on my webview.Please help me regarding this ,

    • javatechig

      Mahesh G V P

      Having next and previous button for navigating through multiple images is just a html/javascript trick. we really have to do anything from android client. Once a url loaded to WebView, it takes care of itself.

      And yes dont forget that we have to override the shouldOverrideUrlLoading() method. This method allows performing your own action when a particular URL is selected. Check out the WebViewClient implementation

      private class MyWebViewClient extends WebViewClient {

      public boolean shouldOverrideUrlLoading(WebView view, String url) {
      return true;

      public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(, menu);
      return true;

  • disqus_xFE06nh1yG

    Hi, i’m trying to load 2 urls in one webview. Each url is pointing to an image, so i want to load both images into the webview. I don’t know if i’m explaining myself in what i’m trying to do, but any help is appreciated.

    • javatechig

      Can you explain your problem clearly? Are you not getting those images loaded to WebView ?

      • disqus_xFE06nh1yG

        yes. I am making an app that grabs an image url from a website and loads it in the webview. For Example, i make


        and it works correctly: it loads the image. But what if i want to load it twice? (so that there are two of the same image) or two different images from two different urls? as in
        image 1:×76.png
        image 2:

        so that they both appear in the same webview.

        • javatechig

          I don’t see there a problem. If you want to load two images on the Android WebView, then you may have to use two tag in your target html and load html from webview.

          In Android WebView at a time you cannot load two different URLs. Any one will be displayed.

          • disqus_xFE06nh1yG

            oh! thank you very much! i hadn’t thought of that before! i just built a dynamic string with the different image files and it worked! thanks!

  • c1ph4

    Unfortunately your code in “3.” does not work.

    In Android 4.1.2 emulator the app crashes. There are no warnings whatsoever in the logging console of Eclipse.

    Also, hardcoding strings in “android:hint” and “android:text” is not recommended. Use “@string/…” and write your texts/hints in strings.xml.

    There is also another warning inside main.xml:

    “The view name (@+id/urlField) suggests this is a URI, but it does not include ‘textUri’ in the inputType”

    I have no idea what that means.

    Don’t get me wrong: I like this example! It’s just that your code doesn’t work. Maybe you should review it.

    • Javatechig

      check your AndroidManifest.xml for internet permission. that can cause this problem. After adding permission if still the problem persists, then check your logs.logs speaks out the issue.

      Examples used here are for demonstration purpose. And yes, you can always improvise in all ways while using. However, thank you for your comment.

      • c1ph4

        Permission in AndroidManifest is already there.

        There are several messages in the log box which are all red. The serious one is this, I think:

        “FATAL EXCEPTION”: main.

        The log before that says:

        java.lang.RuntimeException: Unable to start activity ComponentInfo{}: android.view.InflateException: Binary XML file line #11: Error inflating class uses-permission

        Maybe you are able to help. Otherwise I will have to look for other solutions. He seems to ignore my permission for going online.

        Thanks in advance!

  • muhammad okfriansyah

    1 problem again though. how to add proxy (just using hardcode) to sync in webview?

    • Javatechig

      May be you are missing to provide the permission in main feast


      If you have accessing proxy problem in simulator while accessing webViews, then you may specify DNS server configuration settings in for Android simulators. You can follow below steps
      • Eclipse > Preferences > Android > Launch > Default emulator options:
      • dns-server
      You can add “-dns-server” for any Android Run Configurations already created.
      • Run > Run Configurations > Select Android Project > Target Tab > Additional Emulator Command Line Options:
      • Add “-dns-server” here.

If you like this site please help us clicking on any of these buttons!