Building web apps in WebView

By Building web apps in WebView

There is a common scenario where you want to display information in your app. You might need to update, for instance, privacy and policy information. If you're going to deliver a web page as part of your Android Application, you can use WebView. The WebView class is an extension of Android’s View class. WebView allows Android developers to display web pages as part of their activity layout. WebView just shows a web page by default without features of a fully developed web browser like Google Chrome for Android. 

We can load a remote URL, a URL from our project, or also specify HTML string and show it using WebView. In this tutorial, we shall show how to get started with WebView. We shall also learn how to handle such things like page navigation, binding JavaScript, and indeterminate progress bar when loading URL. 

Adding WebView element to XML

The following is the xml code for a basic WebView:

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

Start by creating a new project in Android Studio. Then open your AndroidManifest.xml file and add permission for internet like this.

<uses-permission android:name="android.permission.INTERNET" />

Now open your activity_main.xml  and create a prograss bar and webview. You can do this by dragging and drop from the design palette or copy and paste the following code to your file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".MainActivity"
    android:orientation="vertical">
    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_height="wrap_content"
        style="@android:style/Widget.ProgressBar.Small" />
    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webView" />
</LinearLayout>


Now we have created a progress bar and web view in our layout. We proceed to write code to load a web page onto this web view. 

Displaying web page on WebView

We shall use loadUrl() method to load the URL on this webview.

WebView webView = findViewById(R.id. webView);
webView.loadUrl("https://blog.ericmuchenah.com/");

We can load static HTML string on webview using loadData() method like this.

WebView webView = findViewById(R.id. webView);
String HTMLString = "<html><body><h1>Hello Web Page</h1>" +
        "<h1>Heading 1</h1><h2>Heading 2</h2><h3>Heading 3</h3>" +
        "<p>This is a sample paragraph of static HTML In Android Web view</p>" +
        "</body></html>";
webView.loadData(HTMLString, "text/html", "UTF-8");

We can load remote URL on webview using WebViewClient like this.

WebView webView = findViewById(R.id. webView);
webView.setWebViewClient(new MyWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://blog.ericmuchenah.com/");
private class MyWebViewClient extends WebViewClient {
 @Override
 public boolean shouldOverrideUrlLoading(WebView view, String url) {
 view.loadUrl(url); 
 return true;
 }

WebViewClient helps us to check events in a WebView. You should override shouldOverrideUrlLoading() method. This method gives us an opportunity to perform our actions when a particular url is selected. setWebViewClient() method is used to set the WebViewClient in the WebView.

Navigating in WebView when history exists

You can navigate to one page back if a back history exists by using goBack() method. You use canGoBack() to check whether there is a back history before navigating back. The following is the code.

if (webView.canGoBack()) {
   webView.goBack();
}

You can navigate to one page forward if a forward history exists by using goForward() method. You use canGoForward() to check whether there is a back history before navigating forward. The following is the code.

if (webView.canGoForward()) {
webView.goForward();
}

Clearing WebView history

You will use clearHistory() method to clear the web view forward and backward history like this.

webView.clearHistory();

Complete code for Android WebView in Java

The following is the complete code for the MainActivity.java. Please copy and paste it in this fie.

package com.example.webviewapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
    WebView webView;
    WebSettings webSettings;
    ProgressBar progressBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportActionBar().hide();
        webView = findViewById(R.id.webView);
        progressBar = findViewById(R.id.progressBar);
        progressBar.setProgress(0);
        webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.setWebViewClient(new MyWebViewClient());
        String url = "https://blog.ericmuchenah.com/";
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl(url);
    }
    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the Back button and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        // If it wasn't the Back key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            progressBar.setProgress(0);
            progressBar.setVisibility(View.VISIBLE);
        }
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressBar.setProgress(100);
            progressBar.setVisibility(View.GONE);
        }
    }
}

Output

When you run the application you will see the following.

Conclusion

In this tutorial, we learnt how to use Android WebView to display a webpage. You can use this application to convert a whole website into an app in minutes if the site is mobile-friendly. 

Thank you for reading this article. Please vote below and share it with your friends and fellow android developers.

Was this article helpful?
Donate with PayPal: https://www.paypal.com/donate

Bessy
Eric Murithi Muchenah

Life is beautiful, time is precious. Make the most out of it.