Android WebView Example

This tutorial below explains Android WebView Example and answers to some of the commonly asked questions on android WebView. In android WebView is an embedded browser that can render static HTML data or even remote URL.

1. What is a WebView?

A WebView is an android UI component that displays webpages. It can either display a remote webpage or can also load static HTML data. This encompasses the functionality of a browser that can be integrated to application. Most of the android applications like WordPress, Flipboard, fiddly; Google Reader, etc. are integrated with WebView in order to display certain piece of online contents. 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.

2. Can we customize Android WebView?

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

You can have a look into the android platform source code from below links
Webkit JNI code
BrowserWebView.Java

3. Invoking the Browser application in android

At times during application development, you may fall into a requirement to invoke the device browser with a specified URL. For example, while using in app advertising, we my redirect user to the vendor website to show more info. Such case we probably go to invoke the mobile browser and load the remote URL

public class WebViewActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Button openUrl = (Button) findViewById(R.id.goButton);
		openUrl.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {				
				Uri uri = Uri.parse("http://javatechig.com");
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(intent);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.web_view, menu);
		return true;
	}

}

4. Loading static HTML data in Android WebView

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" >

    <EditText
        android:id="@+id/urlField"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:hint="Enter URL to open" />

    <Button
        android:id="@+id/goButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Open" />

</LinearLayout>

In my activity class, we are using loadData method. It takes html string data, mime-type and encoding param as three parameters.

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);
                String customHtml = "<html><body><h1>Hello, WebView</h1>" +
                               "<h1>Heading 1</h1><p>This is a sample paragraph.</p>" +
                               "</body></html>";
		webView.loadData(customHtml, "text/html", "UTF-8");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}
}

Output of the above code is

 webview-loading-static-html

5. Loading remote URL in android WebView

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".WebViewActivity" >

    <LinearLayout
        android:id="@+id/urlContainer"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/urlField"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:hint="Enter URL to open" />

        <Button
            android:id="@+id/goButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Open" />
    </LinearLayout>

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

</RelativeLayout>

In my example above, I have created a sample layout with EditText, Button and a WebView. Once enters the URL in the text field and clicks the buttons, the content from the requested URL is getting loaded to the WebView.

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;

public class WebViewActivity extends Activity {
	private WebView webView;
	private EditText urlEditText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_webview);

		urlEditText = (EditText) findViewById(R.id.urlField);
		webView = (WebView) findViewById(R.id.webView);		

		Button openUrl = (Button) findViewById(R.id.goButton);
		openUrl.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				String url = urlEditText.getText().toString();
				if(validateUrl(url)){
					webView.getSettings().setJavaScriptEnabled(true);
					webView.loadUrl(url);
				}
			}
			private boolean validateUrl(String url) {
				// write your url validation code here
				return true;
			}
		});		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.web_view, menu);
		return true;
	}
}

Output of the above code is here

webview-loading-url

6. Some Common Problems

6.1. Clicking URLs in WebView opens in default browser

It is an android default behavior, that it opens the links in default android browser when links are clicked from a WebView. If we want to such annoying characteristics, and always open the links in the browser field instead redirected to the default browser, then we have intercept the click events.

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.

After changes

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;

public class WebViewActivity extends Activity {
	private WebView webView;
	private EditText urlEditText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_webview);

		urlEditText = (EditText) findViewById(R.id.urlField);
		webView = (WebView) findViewById(R.id.webView);
		webView.setWebViewClient(new MyWebViewClient());

		Button openUrl = (Button) findViewById(R.id.goButton);
		openUrl.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				String url = urlEditText.getText().toString();
				if(validateUrl(url)){
					webView.getSettings().setJavaScriptEnabled(true);
					webView.loadUrl(url);
				}
			}
			private boolean validateUrl(String url) {
				return true;
			}
		});		
	}

	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;
	}
}

7. How to Display HTML in Android TextView

Checkout my post from link

http://javatechig.com/android/display-html-in-android-textview/

8. References

http://developer.android.com/reference/android/webkit/WebView.html

http://developer.android.com/guide/webapps/webview.html

A blogger, bit of a tech freak and a software developer. He has around 7+ years of experience in design, development and maintenance of Mobile applications. Follow him on Twitter or Google plus.

  • 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.