Android WebView - Load From URL, Strings and Asset Folder


WebView is actually one of those classes that have existed in android since the beginning.

Added in API level 1, it resides in android.webkit package. It is used to display web content right within the activity. This makes it very powerful and can be used to build even a basic browser that works. It is still a view so we can simply drag it over from the pallete to our layout. It renders web pages using webkit rendering engine. In this example we use a webview to render web content from :

  • URL online.
  • Local Assets folder.
  • String within java code.

To load from url, you must android internet permission in the androidmanifest.xml. You can find more details about WebView here.

Screenshot

  • Here's the screenshot of the project.

Android WebView Example

Android Demo

Common Questions this example explores

  • What is WebView?
  • How to load website from url in webview.
  • How to load html from assets frolder in webview.
  • How to load html string in webview.
  • How to use webview in android activity.

Tools Used

This example was written with the following tools:

  • Windows 8
  • AndroidStudio IDE
  • Genymotion Emulator
  • Language : Java

Libaries Used

  • No third party library was used in this project.

Source Code

Lets jump directly to the source code.

AndroidManifest.xml

  • Android Manifest File.
  • Add Internet permission as we shall fetch a webpage also from url.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutorials.hp.webviewer">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

Build.Gradle

  • Normally in android projects, there are two build.gradle files. One is the app level build.gradle, the other is project level build.gradle. The app level belongs inside the app folder and its where we normally add our dependencies and specify the compile and target sdks.
  • Also Add dependencies for AppCompat and Design support libraries.
  • Our MainActivity shall derive from AppCompatActivity while we shall also use Floating action button from design support libraries.
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.tutorials.hp.webviewer"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.android.support:design:26.+'
    testCompile 'junit:junit:4.12'
}

MainActivity.java

  • Launcher activity.
  • ActivityMain.xml inflated as the contentview for this activity.
  • We initialize views and widgets inside this activity.
  • We switch through menu items in our toolbar, selecting to load from url,assets or string.
package com.tutorials.hp.webviewer;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

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

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
    }

    /*
    LOAD WEBSITE
     */

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.urlID) {
            //LOAD FROM URL
            webView.loadUrl("http://camposha.info");

            return true;
        }else if (id == R.id.assetsID) {

            //LOAD FROM ASSETS
            webView.loadUrl("file:///android_asset/Campo.html");

            return true;
        }else if (id == R.id.stringID) {

            //LOAD FROM STRING
            String html="<html><title></title><body>" +
                    "<h1><u>Programming Languages</u></h1>" +
                    "Below are some languages check them out: " +
                    "<ol>" +
                    "<li>Java</li><li>C#</li><li>C++</li><li>Python</li><li>PHP</li><li>Perl</li>" +
                    "</ol>" +
                    "</body></html>";
            webView.loadData(html,"text/html","UTF-8");

            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

ActivityMain.xml

  • Template layout.
  • Contains our ContentMain.xml.
  • Also defines the appbarlayout, toolbar as well as floatingaction buttton.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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="com.tutorials.hp.webviewer.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

ContentMain.xml

  • Content Layout.
  • Defines the views and widgets to be displayed inside the MainActivity.
  • In this case its a simple webview.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.tutorials.hp.webviewer.MainActivity"
    tools:showIn="@layout/activity_main">

    <WebView
        android:id="@+id/myWebview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        />

</android.support.constraint.ConstraintLayout>

menu_main.xml"

  • We shall be switching through menu items in our toolbar.
  • Let's define this in menu_main.xml inside the menu's directory.
<menu 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"
    tools:context="com.tutorials.hp.webviewer.MainActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
    <item
        android:id="@+id/urlID"
        android:title="URL"
        app:showAsAction="never" />

    <item
        android:id="@+id/assetsID"
        android:title="Assets"
        app:showAsAction="never" />

    <item
        android:id="@+id/stringID"
        android:title="String"
        app:showAsAction="never" />
</menu>

Download

  • Download the Project below:
No. Location Link
1. GitHub Direct Download
2. GitHub Browse

How To Run

  1. Download the project above.
  2. You'll get a zipped file,extract it.
  3. Open the Android Studio.
  4. Now close, already open project.
  5. From the Menu bar click on File >New> Import Project.
  6. Now Choose a Destination Folder, from where you want to import project.
  7. Choose an Android Project.
  8. Now Click on “OK“.
  9. Done, your done importing the project,now edit it.

Conclusion.

We saw a simple android webview example. How to load webpages from online via url, from assets folder and from string data.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post