Tutorial

Android WebView Example Tutorial

Published on August 3, 2022
author

Anupam Chugh

Android WebView Example Tutorial

Android WebView is used to display HTML in an android app. We can use android WebView to load HTML page into android app.

Android WebView

Android WebView component is a full-fledged browser implemented as a View subclass to embed it into our android application.

Importance Of Android WebView

For HTML code that is limited in terms of scope, we can implement the static method fromHtml() that belongs to the HTML Utility class for parsing HTML-formatted string and displaying it in a TextView. TextView can render simple formatting like styles (bold, italic, etc.), font faces (serif, sans serif, etc.), colors, links, and so forth. However, when it comes to complex formatting and larger scope in terms of HTML, then TextView fails to handle it well. For example browsing Facebook won’t be possible through a TextView. In such cases, WebView will be the more appropriate widget, as it can handle a much wider range of HTML tags. WebView can also handle CSS and JavaScript, which Html.fromHtml() would simply ignore. WebView can also assist with common browsing metaphors, such as history list of visited URLs to support backwards and forwards navigation. Still WebView comes with its own set of cons such as it’s a much more expensive widget to use, in terms of memory consumption than a TextView. The reason for this increased memory is because WebView is powered by WebKit/Blink that are open source Web rendering engine to power content in browsers like Chrome.

Android WebView Example

Android WebView component is inserted into the XML layout file for the layout we want the WebView to be displayed in. In this example we insert it into the activity_main.xml file as shown below:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <WebView
        android:id="@+id/webview"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

Android Studio WebView Code

WebView component is initialized in the MainActivity using its id defined in the activity_main.xml as shown in snippet below:

WebView webView = (WebView) findViewById(R.id.webview);

Android WebView loadUrl

Once we’ve obtained a reference to the WebView we can configure it and load URLs via HTTP. WebView loadUrl() method is used to load the URL into the WebView as shown below:

webView.loadUrl("https://www.journaldev.com");

Before we start toying around with the url there are two critical aspects we should take a look at:

  1. Supporting JavaScript: JavaScript is by default turned off in WebView widgets. Hence web pages containing javascript references won’t work properly. To enable java script the following snippet needs to be called on the webview instance:

    getSettings().setJavaScriptEnabled(true);
    
  2. Adding Permissions: To fetch and load the urls in the WebView we need to add permissions to access the internet from within the app else it won’t be able to load the webpages. The following line of code needs to be added in the AndroidManifest.xml file above the application tag as shown below:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="https://schemas.android.com/apk/res/android"
        package="com.journaldev.webview" >
    
        <uses-permission android:name="android.permission.INTERNET" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name=".MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>
    

The MainAcivity class below contains all the features discussed till now.

package com.journaldev.webview;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends Activity {

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

        WebView webView = (WebView) findViewById(R.id.webview);

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        webView.loadUrl("https://www.journaldev.com");
    }

}

Setting the WebViewClient

The default behavior when a user clicks on a link inside the webpage is to open the systems default browser app. This can break the user experience of the app users. To keep page navigation within the WebView and hence within the app, we need to create a subclass of WebViewClient, and override its shouldOverrideUrlLoading(WebView webView, String url) method. Here is how such a WebViewClient subclass would look:

private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url) {
        return false;
    }
}

When the shouldOverrideUrlLoading() method returns false, the URLs passed as parameter to the method is loaded inside the WebView instead of the browser. To distinguish between the URLs that are loaded within the app and browser the following code needs to be added in the shouldOverrideUrlLoading() method:

if(url.indexOf("journaldev.com") > -1 ) return false;
        return true;

Note: Returning true doesn’t signify that the url opens in the browser app. In fact the url won’t be opened at all. To load the url into the browser an intent needs to fired. The following subclass contains all the configurations we’ve added.

package com.journaldev.webview;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;


public class WebViewClientImpl extends WebViewClient {

    private Activity activity = null;

    public WebViewClientImpl(Activity activity) {
        this.activity = activity;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url) {
        if(url.indexOf("journaldev.com") > -1 ) return false;

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        activity.startActivity(intent);
        return true;
    }

}

The constructor takes Activity as a parameter to fire an intent in the browser. Before instantiating this subclass in the MainActivity lets look at another important feature.

If we click the back button in the app developed so far we see that the application returns to the home screen even though we’ve navigated through a few pages within the WebView itself. To go through the browsing history on pressing back button we need to modify the back button function as shown in the snippet below:

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {
            this.webView.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

The onKeyDown() method has been overridden with an implementation that first checks if the WebView can go back. If the user has navigated away from the first page loaded inside the WebView, then the WebView can go back. The WebView maintains a browsing history just like a normal browser. If there is no history then it will result in the default behavior of back button i.e. exiting the app. Following is the code for MainActivity with the above features included.

package com.journaldev.webview;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends Activity {

    private WebView webView = null;

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

        this.webView = (WebView) findViewById(R.id.webview);

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        WebViewClientImpl webViewClient = new WebViewClientImpl(this);
        webView.setWebViewClient(webViewClient);

        webView.loadUrl("https://www.journaldev.com");
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {
            this.webView.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

}

Below image shows the output produced by our project, you can see that WebView is loaded with a preassigned url. android webview example

Alternatives for Loading Content in the WebView

Till now we’ve just used loadUrl() method to load the contents in the WebView. Here we’ll see the other ways to load content after a quick briefing of the usages of loadUrl(). loadUrl() works with:

  • https:// and https://URLs
  • file:// URLs pointing to the local filesystem
  • file:///android_asset/ URLs pointing to one of your applications assets
  • content:// URLs pointing to a ContentProvider that is publishing content available for streaming

Instead of loadUrl() we can use loadData() by which we can display snippets or whole of the HTML code in the method. There are two flavors of loadData(). The simpler one allows us to provide the content, the MIME type, and the encoding, all as strings. Typically, MIME type will be text/html and the encoding will be UTF-8 for ordinary HTML as shown below:

webView.loadData("<html><body>Hello, world!</body></html>",
                  "text/html", "UTF-8");

Below is the output when the above snippet is added in the MainActivity as shown below:

package com.journaldev.webview;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends Activity {

    private WebView webView = null;

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

        this.webView = (WebView) findViewById(R.id.webview);

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        WebViewClientImpl webViewClient = new WebViewClientImpl(this);
        webView.setWebViewClient(webViewClient);

        //webView.loadUrl("https://www.journaldev.com");
        webView.loadData("<html><body>Hello, world!</body></html>", "text/html", "UTF-8");
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {
            this.webView.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

}

android webview There is also a loadDataWithBaseURL() method. This takes, among other parameters, the base URL to use when resolving relative URLs in the HTML. Any relative URL (e.g., <img src=“images/sample.png”>) will be interpreted as being relative to the base URL supplied to loadDataWithBaseURL(). The historyUrl parameter is the URL to write into the WebView internal navigation history for the HTML loaded into the WebView. The following snippet shows a prototype for it:

String baseUrl    = "https://www.journaldev.com";
String data       = "Relative Link";
String mimeType   = "text/html";
String encoding   = "UTF-8";
String historyUrl = "https://www.journaldev.com";

webView.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);

This brings an end to android WebView example tutorial. You can download final android webview project from below link.

Download Android WebView Example Project

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Anupam Chugh

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
July 14, 2017

sir how can we download the full android tutorial as a pdf

- chelsi

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    November 4, 2017

    Hola Como podria lograr: mi html guarda datos en localstorage pero con su codigo no logra hacerlo alguna Idea para llegar al exito Me Gusta Saludos Cordiales!! ##Translate## Hello How could I achieve: my html save data in localstorage but with his code he can not do it Some Idea to get to success I like it Best regards!!

    - WinFix

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      December 22, 2017

      The code i am looking for, thanks for sharing.

      - Bindeshwar Singh Kushwaha

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        February 7, 2018

        Very Nice Tutorial. Thanks for sharing code.

        - Vijay Maurya

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          September 13, 2018

          Hi Thanks for that, this helps me a lot. One more question regarding this project. How to implement files handling into this project? I mean when I have webview project for my website and there is form to upload eg. picture (button select file), when i press this button in chrome, it opens a dialog box to select file from my phone. This is not working in webview app… Any hint how to solve this? Or can you implement this function into your example project? Thank you

          - Tony

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            December 24, 2018

            thank you for the posting this! How we can add a loading/progress indicator to this?

            - Waruna

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              December 27, 2018

              Sir, How will put preloader, because we did know given url it is fully loaded or not. By Waitload.blogspot.com

              - Naveen

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                January 10, 2019

                hello sir. thanks for your help. but i have a problem with back button. i used onKeyDown but it’s not work.

                - dat

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  January 31, 2019

                  Hello, It was a helpful tutorial. I replaced a website in your code. The website is loading in WebView but website load time is slower than the load time in Mobile chrome browser. I tried many solutions from forums etc but nothing worked out. Could you please let me know how to optimize your code so that load time of a website in android app is same a mobile Chrome browser. Thanks in advance

                  - AMJ

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    April 12, 2019

                    Can I link java activity in HTML href ?

                    - JD

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Become a contributor for community

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      DigitalOcean Documentation

                      Full documentation for every DigitalOcean product.

                      Resources for startups and SMBs

                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                      Get our newsletter

                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                      New accounts only. By submitting your email you agree to our Privacy Policy

                      The developer cloud

                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Get started for free

                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                      *This promotional offer applies to new accounts only.