Showing Progress Bar and Preventing the opening of Web Browser on loading URL in WebView of Android

August 28, 2012
By

In this article we will develop an Android application which facilitates users to load a webpage or image in a WebView widget by entering its url. While loading the url, the application will display a progress bar on the title bar to show the percentage of url downloaded.

The requested url will be opened in a web browser if the requested url contains any redirections. In order to prevent this opening of web browser , we need to override the method shouldOverrideUrlLoading() to return false.

Since this application loads the url from the Internet, it requires the permission android.permission.INTERNET, which can be defined in the the file AndroidManifest.xml.

If you want to display an indeterminate progress bar, please read the article titled “Showing indeterminate progress bar on title bar while loading URL in WebView

This application is developed in Eclipse ( 4.2.0 ) with ADT plugin ( 20.0.3 ) and Android SDK ( R20.0.3) .


1. Create a new Android application project namely “WebViewProgress”

New Android Application Project

Figure 1 : New Android Application Project


2. Design application launcher icon

Design Application Launcher Icon

Figure 2 : Design Application Launcher Icon


3. Create a blank activity for defining MainActivity

Create a blank Activity

Figure 3 : Create a blank Activity


4. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details


5. Remove the Android’s Support library from this project, if exists

By default Eclipse ( 4.2.0) adds Android Support Library to  Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click on the file and then clicking the menu item “delete”.


6. Update the file res/values/strings.xml


<resources>
    <string name="app_name">WebViewProgress</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">WebView Demo</string>
    <string name="str_hnt_et_url">Enter URL</string>
    <string name="str_et_url">http://</string>
    <string name="str_btn_load">Load URL</string>
</resources>


7. Update the layout file res/layout/activity_main.xml


    <RelativeLayout 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" >
        <EditText
            android:id="@+id/et_url"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="@string/str_hnt_et_url"
            android:text="@string/str_et_url"
            android:inputType="textUri"
        />

        <Button
            android:id="@+id/btn_load"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/str_btn_load"
            android:layout_below="@id/et_url"
        />

        <WebView
            android:id="@+id/wv_url"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            tools:context=".MainActivity"
            android:layout_below="@id/btn_load"
        />
</RelativeLayout>


8. Update the class MainActivity in the file src/in/wptrafficanalyzer/webviewprogress/MainActivity.java


package in.wptrafficanalyzer.webviewprogress;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    WebView mWvUrl;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /** Enabling Progress bar for this activity */
        getWindow().requestFeature(Window.FEATURE_PROGRESS);

        setContentView(R.layout.activity_main);

        mWvUrl = (WebView) findViewById(R.id.wv_url);

        /** Enabling Javascript for the WebView */
        mWvUrl.getSettings().setJavaScriptEnabled(true);

        OnClickListener btnLoadClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {

                /** Getting reference to edittext widget
                  * of the layout activity_main.xml
                * */
                EditText etUrl = (EditText) findViewById(R.id.et_url);

                /** Load the url entered in the edittext box */
                mWvUrl.loadUrl(etUrl.getText().toString());
            }
        };

        Button btnLoad = (Button) findViewById(R.id.btn_load);
        btnLoad.setOnClickListener(btnLoadClickListener);

        final Activity activity = this;

        mWvUrl.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {

                /** The value of progress for webview varies from 0 to 100
                  * The value of progress for the activity varies from 0 to 10000
                  * So, progress value of webview has to be multiplied by 100
                  */
                activity.setProgress(progress * 100);
            }
        });

        mWvUrl.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                /** This prevents the loading of pages in system browser */
                return false;
            }

            /** Callback method, executed when the page is completely loaded */
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                Toast.makeText(getBaseContext(),
                                    "Page loaded Completely",
                                    Toast.LENGTH_SHORT).show();

                /** Progress reaches to 100% when progress value
                  * is Window.PROGRESS_END (10000) */
                activity.setProgress(Window.PROGRESS_END);
            }

       });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


9. Update the file AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.webviewprogress"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="4"
        android:targetSdkVersion="15" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


10. Screenshots of the application in execution

Entering URL to the application

Figure 5 : Entering URL to the application

Progressing the loading of a URL

Figure 6 : Progressing the loading of a URL


11. Download


12. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , ,

Leave a Reply

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

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner