Android Webview Example Code

Hi there! Today I’m gonna share how to view a website or webpage to your Android apllication. You’ll be able to view webpages from the internet or from the storage of your Adroid device such as your sdcard. This is useful if you want your app not to open a web browser for web links. It is like, the browser is inside or embedded your Android application.

Android Webview Example Code

Android WebView

The following code will enable you to view this blog on your Android Application. This code uses the Android WebView class which is also an extension of Android’s View class.

package com.example.yourproject;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class YourProject extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          //setContentView(R.layout.main);
        
          // Let's display the progress in the activity title bar, like the
          // browser app does.
          getWindow().requestFeature(Window.FEATURE_PROGRESS);

          WebView webview = new WebView(this);
          setContentView(webview);
        
          webview.getSettings().setJavaScriptEnabled(true);

          final Activity activity = this;
          webview.setWebChromeClient(new WebChromeClient() {
          public void onProgressChanged(WebView view, int progress) {
               // Activities and WebViews measure progress with different scales.
               // The progress meter will automatically disappear when we reach 100%
               activity.setProgress(progress * 1000);
          }
        });
        
webview.setWebViewClient(new WebViewClient() {
          
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
          //Users will be notified in case there's an error (i.e. no internet connection)
          Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
 });
       //This will load the webpage that we want to see
        webview.loadUrl("http://codeofaninja.blogspot.com/");

     }
}

If you want to view an html page from your sdcard, you can change the url for example “file:///sdcard/YourProject/index.html“. Well that’s it. Thanks for reading. :)

DOWNLOAD SOURCE CODE

Resources:
http://developer.android.com/guide/webapps/webview.html
http://developer.android.com/reference/android/webkit/WebView.html

Instant Android Webview Code

Hi guys! Today I want to share a class I created to help me whenever I have a WebView activity in my app. I simply call it a WebView helper class. The main benefit of having a class like this for your web views is that, you won’t have to specify the same code over and over again for each of your web view activities. You are re-using the web view code that shortens and make our code look cleaner. You can just use one settings for all your web views, and at the same time, you can add any JavaScript interfaces and specify the URL to be loaded.

What loading pages will look like.

What loading pages will look like.

How to use?

For the sake of starting android programmers, I will include the whole code of our MainActivity:

package com.codeofaninja.app;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.webkit.WebView;
public class MainActivity extends Activity {

     WebView web;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      
        // initialize our helper class
        // then call the webview() methods with our context as parameter (MainActivity.this)
        web = new WebViewHelper().webview(MainActivity.this);
      
        // specify the url we want to load
        web.loadUrl(“http://codeofaninja.com/”);
      
        // you can add JavaScript interface like this:
        // web.addJavascriptInterface(new YourJsInterfaceClass(), “Android”);

        // set web as content view
        setContentView(web);
      
    }
  
}

Our WebViewHelper.java code:

package code.of.a.ninja.Utils;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.RenderPriority;
import android.widget.Toast;

public class WebViewHelper {

    private ProgressDialog mProgressDialog;

    //make it final so it will be accessible to setWebViewClient
    public WebView webview(final Context mContext) {

        // progress dialog
        mProgressDialog = new ProgressDialog(mContext);

        // new webview
        WebView web = new WebView(mContext);

        // web settings
        WebSettings webSettings = web.getSettings();

        // false
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setAppCacheEnabled(false);

        // true
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);

        // other
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setRenderPriority(RenderPriority.HIGH);

        web.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                //show the user progress percentage
                mProgressDialog.setMessage(“Loading… “ + progress + “%”);
            }
        });

        web.setWebViewClient(new WebViewClient() {

            public void onReceivedError(WebView view, int errorCode,
                    String description, String failingUrl) {

                //if there’s an error loading the page, make a toast
                Toast.makeText(mContext, description + “.”, Toast.LENGTH_SHORT)
                        .show();

            }

            public void onPageFinished(WebView view, String url) {
                //after loading page, remove loading page
                mProgressDialog.dismiss();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                super.onPageStarted(view, url, favicon);

                //on page started, show loading page
                mProgressDialog.setCancelable(false);
                mProgressDialog.setMessage(“Loading…”);
                mProgressDialog.show();

            }

        });

        // return the web view
        return web;
    }
}

That’s it! Enjoy using our web view helper class!

3 replies
  1. Francisco Corrales
    Francisco Corrales says:

    You know what would be great ?, if we could download the .apk file ! why don’t you put them in here ! or in Google Play !?

    Reply
    • ninjazhai
      ninjazhai says:

      Hi @Francisco Corrales, thanks for your suggestion, but do you have any specific reason why you want to download the apk file?

      In my perspective, I want the readers to follow the code example above and test it on their device or emulators so they can feel like achieving and learning something.

      Anyway, I used almost the same code on this blog’s official app, you can download our app on google play here: https://play.google.com/store/apps/details?id=com.thecode.ofaninja

      Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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