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
BrowserWebView.Java

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("http://javatechig.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

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 JavaTechig.com 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="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/urlContainer"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <WebView
        android:id="@+id/webView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
</LinearLayout>

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(R.id.webView);
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>" +
           "</body></html>";
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;	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_webview);
		
		webView = (WebView) findViewById(R.id.webView);
		webView.setWebViewClient(new MyWebViewClient());
		
		String url = "http://javatechig.com";
                webView.getSettings().setJavaScriptEnabled(true);
		webView.loadUrl(url);		
	}

	private class MyWebViewClient extends WebViewClient {
	    @Override
	    public boolean shouldOverrideUrlLoading(WebView view, String url) {
	        view.loadUrl(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. He has over 8 years of experience in developing rich mobile applications in Android, HTML5, Xamarin and PhoneGap.

  • VIshwanath Hiremath

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

    • http://javatechig.com Nilanchala Panigrahy

      The shouldOverrideUrlLoading method gives you the url. Checkout the params

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

  • Edney Imme

    Hello,
    how can i accept cookies in Webview?

  • http://javatechig.com/ JavaTechig

    Dont understand your question quite well..

  • http://javatechig.com/ JavaTechig

    updated with more information.

  • http://javatechig.com/ 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;
    }
    };

  • http://javatechig.com/ javatechig

    You may have a look into the third party lib code

    https://code.google.com/p/android-page-curl/

  • Rzenks Mj

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

    • http://javatechig.com/ 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 = “http://www.example.com/yourfile.pdf”; // your pdf url
      String googleDocsUrl = “http://docs.google.com/viewer?url=”+pdfurl; //url for your webview

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

  • http://javatechig.com/ javatechig

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

  • Alex

    Hello,
    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 ,

    • http://javatechig.com/ 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 {

      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
      view.loadUrl(url);
      return true;
      }
      }

      @Override
      public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.web_view, 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.

    • http://javatechig.com/ 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

        webview.loadUrl(“http://javatechig.com/wp-content/uploads/2013/05/javatechig-logo-full2-300×76.png”);

        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: http://javatechig.com/wp-content/uploads/2013/05/javatechig-logo-full2-300×76.png
        image 2: http://mediacdn.disqus.com/uploads/users/5578/6211/avatar92.jpg?1370843353

        so that they both appear in the same webview.

        • http://javatechig.com/ 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!

  • http://gizmeo.com 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.

    • http://javatechig.com 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.

      • http://gizmeo.com 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{com.example.app/com.example.zapp.MainActivity}: 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?

    • http://javatechig.com Javatechig

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

      WebView.enablePlatformNotifications();

      Option-2
      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 8.8.8.8
      You can add “-dns-server 8.8.8.8″ for any Android Run Configurations already created.
      • Run > Run Configurations > Select Android Project > Target Tab > Additional Emulator Command Line Options:
      • Add “-dns-server 8.8.8.8″ here.