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.
- 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.
- WebView encompasses the functionality of a browser that can be integrated to Android application.
- 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.
- 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).
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");
6. Load Remote URL on WebView
- 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.
- We can do this using android
WebViewClient
. WebViewClient helps to monitor events in a WebView. We have to override theshouldOverrideUrlLoading()
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 thesetWebViewClient()
method. - The WebViewClient class has some other useful methods such as
onPageStarted()
,onPageFinished()
andonReceivedError()
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
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.
Below api level 25 i am not able to load html page. Any clue ?
Below api level 25 i am not able to load html page. Any clue ?
Thank you for web view web client, you save my day.
Thank you.
hi, Can you help me with displaying document (docx) file in Text view ?
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… Read more »
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 ?
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..!!
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… Read more »
How to get the URL of the web page after navigation through hyperlinks in webview
The shouldOverrideUrlLoading method gives you the url. Checkout the params
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
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… Read more »
Hello,
how can i accept cookies in Webview?
Dont understand your question quite well..
updated with more information.
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;
}
};
You may have a look into the third party lib code
https://code.google.com/p/android-page-curl/
How can i use strings from one activity(class) to another and open the strings in webview ?
Please use intent bundle to pass data between activities.
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?
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.
What if the pdf file is in a https site?
Thanks
According to my knowledge u cant. Please check the android developer portal documentation.
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
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… Read more »
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()… Read more »
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.
Can you explain your problem clearly? Are you not getting those images loaded to WebView ?
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… Read more »
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… Read more »
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!
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… Read more »
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… Read more »
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… Read more »
You can check out a working copy from Github https://github.com/javatechig/javatechig-android-ui/tree/master/AndroidWebview
Thanks!
I will try this as soon as I can!
Thanks for this link!
Kindest regards
You broke it yourself, you have put the in a layout XML file, and not the AndroidManifest.xml file…
1 problem again though. how to add proxy (just using hardcode) to sync in webview?
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 >… Read more »