Tutorials Android Android WebView Example

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://stacktips.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 stacktips.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://stacktips.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.

Total
0
Shares
guest
39 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
muhammad okfriansyah
muhammad okfriansyah
9 years ago

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

user
user
9 years ago

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.

c1ph4
c1ph4
9 years ago

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.

user
user
9 years ago
Reply to  c1ph4

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
c1ph4
9 years ago
Reply to  user

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!

user
user
9 years ago
Reply to  c1ph4
c1ph4
c1ph4
9 years ago
Reply to  user

Thanks!

I will try this as soon as I can!

Thanks for this link!

Kindest regards

devshark
devshark
8 years ago
Reply to  c1ph4

You broke it yourself, you have put the in a layout XML file, and not the AndroidManifest.xml file…

disqus_xFE06nh1yG
disqus_xFE06nh1yG
9 years ago

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
javatechig
9 years ago

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

disqus_xFE06nh1yG
disqus_xFE06nh1yG
9 years ago
Reply to  javatechig

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://stacktips.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://stacktips.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.

javatechig
javatechig
9 years ago

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
disqus_xFE06nh1yG
9 years ago
Reply to  javatechig

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!

Mahesh G V P
Mahesh G V P
9 years ago

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
javatechig
9 years ago
Reply to  Mahesh G V P

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

Alex
Alex
8 years ago

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

javatechig
javatechig
7 years ago

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

Bil Kimes
Bil Kimes
7 years ago

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
Nilanchala Panigrahy
7 years ago
Reply to  Bil Kimes

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.

Pliachas
Pliachas
6 years ago

What if the pdf file is in a https site?
Thanks

Rzenks Mj
Rzenks Mj
7 years ago

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

javatechig
javatechig
7 years ago
Reply to  Rzenks Mj

Please use intent bundle to pass data between activities.

javatechig
javatechig
7 years ago

You may have a look into the third party lib code

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

javatechig
javatechig
7 years ago

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
JavaTechig
7 years ago

updated with more information.

JavaTechig
JavaTechig
7 years ago

Dont understand your question quite well..

Edney Imme
Edney Imme
7 years ago

Hello,
how can i accept cookies in Webview?

VIshwanath Hiremath
VIshwanath Hiremath
7 years ago

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

Nilanchala Panigrahy
Nilanchala Panigrahy
7 years ago

The shouldOverrideUrlLoading method gives you the url. Checkout the params

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

VIshwanath Hiremath
VIshwanath Hiremath
6 years ago

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

Jovanpreet
Jovanpreet
6 years ago

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.

W3i.iN
W3i.iN
6 years ago

Would you please tell me where to get started.. I want to create an webview application for my blog.

Tell me complete guide from beginning..!!

adeet
adeet
6 years ago

hi, i am trying to load a url with a ‘.world’ extension inside a webview but it doesnt work for me. any idea what could be the reason ?

Avinash Soni
Avinash Soni
4 years ago

hi, Can you help me with displaying document (docx) file in Text view ?

phila
phila
4 years ago
Reply to  Avinash Soni

It’s not possible – there are several libraries that (try to) display Office files, but none are perfect.
Unlike iOS, which can display Word, Excel or PowerPoint files in a WebView, Android doesn’t allow it natively.
The simplest option is to let Google Docs display it, but that forces the requirement of Internet access and uploads the document to the server for it to render it.

Minal
Minal
3 years ago

Thank you for web view web client, you save my day.

swetha
swetha
3 years ago

Below api level 25 i am not able to load html page. Any clue ?

swetha
swetha
3 years ago

Below api level 25 i am not able to load html page. Any clue ?

Previous Post
Android Tutorials

Android ListView Example

Next Post
Android Tutorials

Android Toast Example

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
39
0
Would love your thoughts, please comment.x
()
x