Skip to main content

Android


https://abhiandroid.com/ui/webview
//

WebView Tutorial With Example In Android Studio

In Android, WebView is a view used to display the web pages in application. This class is the basis upon which you can roll your own web browser or simply use it to display some online content within your Activity. We can also specify HTML string and can show it inside our application using a WebView. Basically, WebView turns application into a web application.
WebView in Android
In order to add Web View in your application, you have to add <WebView> element to your XML( layout ) file or you can also add it in java class.
<WebView
android:id="@+id/simpleWebView"  
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

Internet Permission Required For Webview:

Important Note: In order for Activity to access the Internet and load the web pages in a WebView, we must add the internet permissions to our Android Manifest file (Manifest.xml).
Below code define the internet permission in our manifest file to access the internet in our application.
<!--Add this before application tag in AndroidManifest.xml-->
<uses-permission android:name="android.permission.INTERNET" />
Intenet Permission AndroidManifest Code For WebView

Methods of WebView In Android:

Let’s discuss some common methods of a Webview which are used to configure a web view in our application.
loadUrl() – Load a web page in our WebView
loadUrl(String url)
This function is used to load a web page in a web view of our application. In this method we specify the url of the web page that should be loaded in a web view.
Below we load a url: https://abhiandroid.com/ui/ in our application.
/*Add in Oncreate() funtion after setContentView()*/
// initiate a web view
WebView simpleWebView=(WebView) findViewById(R.id.simpleWebView);
// specify the url of the web page in loadUrl function
simpleWebView.loadUrl("https://abhiandroid.com/ui/");
loadUrl in Webview Android
2. loadData() – Load Static Html Data on WebView
  loadData(String data, String mimeType, String encoding) 
This method is used to load the static HTML string in a web view. loadData() function takes html string data, mime-type and encoding param as three parameters.
Below we load the static Html string data in our application of a web view.
/*Add in Oncreate() funtion after setContentView()*/
// initiate a web view
WebView webView = (WebView) findViewById(R.id.simpleWebView);
// static html string data
String customHtml = "<html><body><h1>Hello, AbhiAndroid</h1>" +
        "<h1>Heading 1</h1><h2>Heading 2</h2><h3>Heading 3</h3>" +
        "<p>This is a sample paragraph of static HTML In Web view</p>" +
        "</body></html>";
// load static html data on a web view
webView.loadData(customHtml, "text/html", "UTF-8");
loadData in WebView Android
3. Load Remote URL on WebView using WebViewClient:
WebViewClient help us to monitor event in a WebView. You have to Override the shouldOverrideUrlLoading() method. This method allow us to perform our own action when a particular url is selected. Once you are ready with the WebViewClient, you can set the WebViewClient in your WebView using the setWebViewClient() method.
Below we load a url by using web view client in a WebView.
/*Add in Oncreate() funtion after setContentView()*/
// initiate a web view
 simpleWebView = (WebView) findViewById(R.id.simpleWebView);

// set web view client
 simpleWebView.setWebViewClient(new MyWebViewClient());

// string url which you have to load into a web view
 String url = "https://abhiandroid.com/ui/";
 simpleWebView.getSettings().setJavaScriptEnabled(true);
 simpleWebView.loadUrl(url); // load the url on the web view
 }

 // custom web view client class who extends WebViewClient
 private class MyWebViewClient extends WebViewClient {
 @Override
 public boolean shouldOverrideUrlLoading(WebView view, String url) {
 view.loadUrl(url); // load the url
 return true;
 }
4. canGoBack() – Move to one page back if a back history exist
This method is used to specify whether the web view has a back history item or not. This method returns a Boolean value either true or false. If it returns true then goBack() method is used to move one page back.
Below we check whether a web view has back history or not.
// initiate a web view
WebView simpleWebView=(WebView)findViewById(R.id.simpleWebView);
// checks whether a web view has a back history item or not
Boolean canGoBack=simpleWebView.canGoBack();
5. canGoForward() – Move one page forward if forward history exist
This method is used to specify whether the web view has a forword history item or not. This method returns a Boolean value either true or false. If it returns true then goForword() method is used to move one page forword.
Below we check whether a web view has forward history or not.
// initiate a web view
 WebView simpleWebView=(WebView)findViewById(R.id.simpleWebView);
// checks whether a web view has a forward history item or not
 Boolean canGoForword=simpleWebView.canGoForward() ;
6. clearHistory() – clear the WebView history
This method is used to clear the web view forward and backward history.
Below we clear the forword and backword history of a WebView.
WebView simpleWebView=(WebView)findViewById(R.id.simpleWebView); // initiate a web view
simpleWebView.clearHistory(); // clear the forward and backward history

WebView Example In Android Studio:

Here in this WebView example we show the use of web view in our application. To do that we display two buttons one is for displaying a web page and other is for displaying static HTML data in a web view. Below is the final output, download code and step by step explanation:
WebView Example in Android Studio
Step 1: Create a new project and name it WebViewExample
Select File -> New -> New Project then Fill the forms and click "Finish" button.
Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code :
In this step we open an XML file and add the code for displaying two buttons and a Webview in our xml file ( layout ).
<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"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2">

        <Button
            android:id="@+id/loadWebPage"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:layout_weight="1"
            android:background="#444"
            android:text="Load Web Page"
            android:textColor="#fff"
            android:textSize="14sp"
            android:textStyle="bold" />

        <Button
            android:id="@+id/loadFromStaticHtml"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_weight="1"
            android:background="#444"
            android:text="Load Static HTML"
            android:textColor="#fff"
            android:textSize="14sp"
            android:textStyle="bold" />
    </LinearLayout>

    <WebView
        android:id="@+id/simpleWebView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginTop="20dp"
        android:scrollbars="none" />

</LinearLayout>
Step 3: Open   src -> package -> MainActivity.java
In this step we open MainActivity and add the code to initiate the web view and two buttons. Out of those one button is used for displaying a web page in a webview and other one is used to load a static HTML page in webview.
package example.gb.webviewexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ButtonBarLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    WebView simpleWebView;
    Button loadWebPage, loadFromStaticHtml;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // initiate buttons and a web view
        loadFromStaticHtml = (Button) findViewById(R.id.loadFromStaticHtml);
        loadFromStaticHtml.setOnClickListener(this);
        loadWebPage = (Button) findViewById(R.id.loadWebPage);
        loadWebPage.setOnClickListener(this);
        simpleWebView = (WebView) findViewById(R.id.simpleWebView);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loadFromStaticHtml:
                // define static html text
                String customHtml = "<html><body><h1>Hello, AbhiAndroid</h1>" +
                        "<h1>Heading 1</h1><h2>Heading 2</h2><h3>Heading 3</h3>" +
                        "<p>This is a sample paragraph of static HTML In Web view</p>" +
                        "</body></html>";
                simpleWebView.loadData(customHtml, "text/html", "UTF-8"); // load html string data in a web view
                break;
            case R.id.loadWebPage:
                simpleWebView.setWebViewClient(new MyWebViewClient());
                String url = "https://abhiandroid.com/ui/";
                simpleWebView.getSettings().setJavaScriptEnabled(true);
                simpleWebView.loadUrl(url); // load a web page in a web view
                break;
        }
    }

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

    
}
Step 4: Open manifests -> AndroidManifest.xml
In this step we open Manifest file and define the internet permission for our app.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.gb.webviewexample">
    <!-- define internet permission for our app -->
    <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>
 Output:
Now start the AVD in Emulator and run the App. Choose either to open webpage or static HTML in WebView by clicking on Button. We open static HTML.
WebView Example Output Android
 

How to add progressBar in webview & convert website into advance android app

Video Thumbnail
Convert-website-into-advance-android-app-banner

Convert Website Into App Using WebView:

Now you have learn WebView, so why not try converting any website into Android App? Read our advance WebView Android App tutorial to learn how to do it easily.

DOWNLOAD THISFREE eBook!

This free eBook will help you master the learning of Android App Development in Android Studio!

7 thoughts on “WebView Tutorial With Example In Android Studio”

  1. Hello sir
    ThAnkyou for this tutorial,
    I have a question-
    Main actvity XML file have 2 buttons frist btn click then open browser activity and show web page I m set a url in browser activity and implement some features of browser activity like bookmarks, scroll down to hide app bar and many more .But
    How to set second button to load diffrent url in same browsers activity
    Plz sir reply
    Waiting for your reply
    Thank you

Leave a Reply

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


Continue Reading:
//

Comments

Popular posts from this blog

web2apk

http://web2apk.com/create.aspx Create App   Intro   About   Changes   MalWare ?   Contact   Privacy Useful Links Bluetooth Mini Keyboards Android Mini PC Reset Android URL App Title Icon or

Android Bar Chart Using MpAndroidChart Library Tutorial

https://www.numetriclabz.com/android-bar-chart-using-mpandroidchart-library-tutorial/ Android Bar Chart Using MpAndroidChart Library Tutorial Objective In this tutorial we learn how to implement Bar Chart using MpAndroidChart Library in your Android App. Download Source Code       Step 1 Contents ·        1  Introduction ·        2  Creating Bar chart o    2.1  Create a new Project o    2.2  Adding library in Project o    2.3  Create Layout o    2.4  To Plot Bar Chart §   2.4.1  Initialize the graph id §   2.4.2  Creating a Dataset §   2.4.3  Defining X-axis labels §   2.4.4  Set the data §   2.4.5  Add the description to the chart §   2.4.6  Run your App § ...

how to retrieve image from sqlite database in android and display in listview

 Android platform provides several ways to store data in our application. 1. SQLite database 2. SharedPreferences etc For our post, we will only work with SQLite database. First and foremost, we need to understand what an SQLite database is? SQLite database  is an open source SQL database that stores data to a text file on a device. It executes SQL Commands to perform a set of functions, that is, create, read, update and delete operations. On my previous post, I showed how to  store data in SQLite database from edit text, retrieve and populate it in a listview . For this post, I will show the SQLite CRUD operations with images from gallery and text from EditText. We need to understand this; images are stored in SQLite database as BLOB data type. A BLOB is a large binary object that can hold a variable amount of data.  Note, we can only store images in the database as BLOB data type. We need to convert our image path to a bitmap th...