How to Use WebView to Create an Android Application

Android Webview

What is a WebView

WebViews in Android development allow you to deliver a web application or render a web page within a client application. It is an extension of Android’s View class that allows you to display web pages as a part of your activity layout. While it does not include any features of a fully developed web browser, such as navigation controls or an address bar, etc, it does conveniently render a web page.

Why Should You Use a WebView?

While Webviews are a necessary aspect of software development, not all mobile applications that you build will require a webview. So when do you use a webview?

  • Use a webview if your app provides data to the user that always requires an Internet connection to retrieve data, such as email.
  • Use a webview if you find that it’s easier tobuild a Webview in your Android app that shows a web page, rather than performing a network request, then parsing the data and rendering it in an Android layout, which requires lots of effort.
  • Use a Webview if you have already built a website for your company or brand and the management decides that it wants a mobile version of the website

Now Let’s Write Some Code …

Create a new Android Studio Project.

Choose Empty Activity

Give your application a name

Click Finish

Android WebView development
Android WebView Development

In your activity_main.xml file insert the following code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

   <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
       android:id="@+id/swipe"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       tools:layout_behavior="@string/appbar_scrolling_view_behavior">

       <WebView
           android:id="@+id/web"
           android:layout_width="match_parent"
           android:layout_height="match_parent"/>


   </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>


    <ProgressBar
        android:id="@+id/progress"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        style="?android:attr/progressBarStyle"
        />

</RelativeLayout>

The WebView component is what renders the WebView.

The SwipeRefresh component enables reloading of the application on vertical swipe.

The ProgressBar is to show progress on when the page is loading.

Now in your MainActivity.java file insert the following code

package [Change to your package name or just ignore this line];

import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    WebView webView;
    ProgressBar progressBar;
    SwipeRefreshLayout swipeRefreshLayout;

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

        webView = findViewById(R.id.web);
        progressBar = findViewById(R.id.progress);
        swipeRefreshLayout = findViewById(R.id.swipe);


        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSupportZoom(false);
        webView.getSettings().setDomStorageEnabled(true);
        webView.setWebViewClient(new myWebViewclient());
        webView.loadUrl("https://codeflarelimited.com");

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeRefreshLayout.setRefreshing(true);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(false);
                        webView.loadUrl("https://codeflarelimited.com");
                    }
                },  3000);
            }
        });

        swipeRefreshLayout.setColorSchemeColors(
                getResources().getColor(android.R.color.holo_blue_bright),
                getResources().getColor(android.R.color.holo_orange_dark),
                getResources().getColor(android.R.color.holo_green_dark),
                getResources().getColor(android.R.color.holo_red_dark)
        );


    }
    public class myWebViewclient extends WebViewClient{
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_LONG).show();
            webView.loadUrl("file:///android_asset/lost.html");
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressBar.setVisibility(View.GONE);
        }
    }
}

Now, the onReceivedError method is called when there is an error in network connection. So instead of allowing the application to throw us some ill-looking error codes, we want to catch that and instead load our own custom error page.

Right click on your res folder in your Android Studio Project. Go to New and create an assets folder

Create a html file called lost.html and insert the following code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Connection Failed</title>
    <style>
  body {
  display: inline-block;
  background: #00AFF9 url('img/gone.png') center/cover no-repeat;
  height: 100vh;
  margin: 0;
  color: white;
}

h1 {
  margin: .8em 3rem;
  font: 4em Roboto;
}
p {
  display: inline-block;
  margin: .2em 3rem;
  font: 2em Roboto;
}
 </style>
</head>
<body>
<center>
    <h2 style="text-align:center;padding:5px;color:#d9534f">The network failed</h2>
    <h2 style="text-align:center;padding:5px;color:#d9534f">Check your network connection and swipe to refresh </h2>
</center>

</body>
</html>

This lost.html file should be inside the assets folder that you just created.

You’re almost done …

Next, add the following snippet in your AndroidManifest.xml file. This snippet sets the internet permission. Your app won’t work well if you forget or fail to add it.

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

Finally …

Run your application

So, there you have it guys. If you have any questions, let me know in the comment section.

Want more video tutorials tutorials subscribe to our YouTube channel

Get practical, one-on-one ICT and software development training in Abuja

Software development tutorials Codeflare

Leave a Reply

Your email address will not be published. Required fields are marked *