Using Android’s WebView, WebChromeClient and WebViewClient to load a webpage and display the progress

Post to Twitter

I’ve been working with the Android SDK and Eclipse tools for a while now. The article today won’t be the most fantastic Android application out there but it will show some potential on how you could harness WebView for your own applications.


Article Updated March 7, 2011 – Misc. corrections in the code.

Make sure you have your Android development environment setup and ready to go. Create a new Android project in Eclipse and name it whatever you wish. I named mine “WebPageLoader”.

You’ll notice I am targeting Android 1.6 and above, feel free to target newer SDK versions if you wish. The first thing we need to do is modify the “main.xml” file located in the “res/layout” folder. Overwrite the existing code with this:

<?xml version="1.0" encoding="utf-8"?>
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>

Now go into the “AndroidManifest.xml” file and add the following line:

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

That line is required because we will be using the Internet therefore we need to have the appropriate permissions set.

Go back into the “WebPageLoader.java” file and paste in this code overwriting the existing code:

package com.giantflyingsaucer;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
 
public class WebPageLoader extends Activity
{
    final Activity activity = this;
 
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.main);
        WebView webView = (WebView) findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
 
        webView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress)
            {
                activity.setTitle("Loading...");
                activity.setProgress(progress * 100);
 
                if(progress == 100)
                    activity.setTitle(R.string.app_name);
            }
        });
 
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
            {
                // Handle the error
            }
 
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                view.loadUrl(url);
                return true;
            }
        });
        
        webView.loadUrl("http://developer.android.com");
    }
}

The code is pretty simple. It loads a webpage, shows the progression of loading the website, etc.

Post to Twitter

This entry was posted in Android, Java. Bookmark the permalink.

36 Responses to Using Android’s WebView, WebChromeClient and WebViewClient to load a webpage and display the progress

  1. Pingback: Using SQLite with Android to power an AutoComplete textbox « Giant Flying Saucer

  2. Juan MIguel says:

    Im new to android and your simple example but im having errors in this part..

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

    id cannot be resolve.

    thanks

  3. Chad Lung says:

    @Juan

    Make sure you have a WebView in the main.xml named appropriately.

    Chad

  4. duck says:

    Iv been looking for this easy quick example of WebView for a week. SO glad to find yours!

  5. In the xml layout, the webView should be WebView.
    Use Capital W and V !.
    I hope this ‘ll proove more useful though.

    Precious Diva

  6. Ricky says:

    Is there anyway to make use of the back button? Trying this but the webview cannot be resolved.
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
    webview.goBack();
    return true;
    }
    return super.onKeyDown(keyCode, event);

  7. kanishka says:

    i did the same thing but its saying “the webpage may be temporarily down”….i even tried opening a web page through the general browser but its not workin..wat is the remedy??

  8. Gavin says:

    Yes please update this to add the back key feature, i have been trying to fit it in with no luck.

  9. Splitt3r says:

    Hey nice tutorial :)

    @Ricky try this:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
    webview.goBack();
    return true;
    }
    return super.onKeyDown(keyCode, event);
    }

  10. Jared says:

    Thanks for the tutorial. Everything seemed to go smoothly until I tried to run the app.

    I went through the tutorial typing all the code manually, then went back and copied/pasted. I keep getting a Force Close when I try to run the app on both my phone and the emulator. Any suggestions?

  11. Chad Lung says:

    @Jared,

    Hmm, could be several things. You can try printing out some debugging info when running on the client, narrow it down to where in the code its crashing.

    Chad

  12. Hzee says:

    I am having the same problem as @Jared. I get the forced close screen too..I cannot figure out what the problem is. @Jared if you know the cause of the problem can you please provide details here.

  13. Jason says:

    I’m having the same issue as Jared and Hzee. Any resolution here? I don’t know how to print my debugging info.

    please advise

  14. Chad Lung says:

    @Jared, @Hzee, @Jason,

    I’ve updated the article and made some corrections.

    @Jason, you can debug using:

    import android.util.Log;

    Then just call something like:

    Log.i(“MyTag”, “My debugging info”);

    Chad

  15. Taz Ryder says:

    my web app wont show up in launcher I’m not sure what I’ve done wrong this is my androidmanifest

  16. James says:

    If I want to show the page without the top bar loading section, how could I do that? Thanks for the great code by the way

  17. Emily says:

    nice tutorial there. would like to ask if there’s any way that would allow us to click buttons? As i tried google site but was unable to click the search button. thanks

  18. Chad Lung says:

    @Emily,

    In the emulator or on an actual device?

    Chad

  19. Pingback: Hur man bygger en enkel app för Android och iPhone av en webbsajt | Gör Om Gör Rätt!

  20. Vinayak says:

    Thanks Chad!!!

  21. love sunset21 says:

    Thanks for the tutorial. I face the same problem with Jared, Hzee and Jason. It stops working unexpectedly. The only thing I do is following the tutorial, copy and paste the code. Could you please give me some suggestion?

  22. Anthony says:

    Is there a way to enable long click to download or save a link?

  23. Rajani says:

    Nice example. I tried this example and its working fine. i want to play video in y own activity using webview.
    My code will be like this.
    webView.loadUrl(“http://www.youtube.com/watch?v=2pk”);
    But its leaving my activity and playing in Youtube .How d I play video in my activity?

    -rajani

  24. Chad Lung says:

    @rajani,

    On my Droid X and I assume other Android based phones I’m given a choice/setting to either watch videos in a browser or the native Youtube app. My guess is this might be what’s overriding your app.

    Chad

  25. peter D says:

    I’d also like to know if there’s a way to enable webview to download files for example a zip file on long click… thans for your help

  26. cstrachan says:

    Hello, thanks for the tut.

    I’m using a loadurl(getstring()) the string has a Url with a & in it. It doesn’t work. Any ideas how to get around this?

  27. Mark says:

    Anyone know how to get a page with flash content working like this? Tried with Honeycomb 3.1 and it’s not working :-(

  28. Sudhakar says:

    Hi Chad,

    Thanks for the nice example.
    I am new to Android. I tried above piece of code, however could not see the webpage in webview. It shows blank/white screen in emulator.

    In native browser, i could open web pages by giving proxy settings.
    Do you think, i need to do anything more to show web page using webview while working with proxy..

  29. Chandan says:

    I am not able to play youtube video using webview. I am able to open youtube in webview but not able to play video. please give me some suggestion. Thanks In advance.

  30. MWEMA says:

    MAKE SURE YOU HAVE NOT SET NO TITLEBAR IN MANIFEST ACTIVITY FOR THE PROGRESS BAR TO SHOW.. GOT ME A BIT MIXED-UP

    THANKS PAL FOR THE TUT! :)

  31. Mike Clarke says:

    I too spent days trying to find a tut like this one.

    I needed a loading screen for my website, something you would think would be the first thing the tuts would help out with when dealing with webview. There are a lot of tutorials out there that are off track, this example is so simple, which I thought it should be. You deserve a pat on the back!

    We need a website for tutorials that have been proven and work! I probably shouldn’t mention it here but the asp.net forum is one forum that works, there should be more forums like that!

    Cheers,

    Mike.

  32. Mike Clarke says:

    Hi,
    I can’t get the following to resolve either.

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
    webview.goBack();
    return true;
    }
    return super.onKeyDown(keyCode, event);
    }

    Please email me you have an answer mike@fnesse.com

    Cheers,

    Mike.

  33. shakti says:

    Thanks for the tutorial.. I am working on similar application. and facing problem when i click on the link which is embedded on the webpage.
    Clicking on the “SDK” tab does not navigate me to the desired page or the other link specified in the “HOME” tab. only the color of the text changes and nothing happens.
    1>Does anyone try navigating to other tab. Or Do i need to add some piece of code (Please let me know).

    2>Will this be handled by android code or the html/php code?

    **The same site “http://developer.android.com/index.html” working fine in browser.
    with Android apk its not working.

    Any help will be highly appreciated.

    Thanks!!!!

  34. shakti says:

    Issue solved.
    Actually i was using –**– view.loadUrl(“javascript:changeLocation(‘” + url + “‘)”); –**–
    instead of view.loadUrl(url ); –**–

    Everything is working fine..

  35. Shou says:

    Hi there. The WebView is working fine as:

    WebViewX.loadUrl(“http://www.sweet-cures.com/index.htm”);

    Is it possible to have the WebView link change depending on what language the phone is set to, using the @+string/..

    I tried this:
    WebViewX.loadUrl(“@string/WebViewX”);

    …But it’s not working. There is a correctly named string in the strings.xml

    Any ideas?

  36. Chad Lung says:

    @Shou,

    Looks like your not using the string resource correctly.
    http://developer.android.com/guide/topics/resources/string-resource.html

    Chad

Comments are closed.