Pages - Menu

Pages - Menu

Wednesday, 13 June 2012

Android Webview Example

Android’s WebView allows you to open an own windows for viewing URL or custom html markup page.That means webview is a View that displays web pages

Today i will tell about a program which will load website through Webview.
The aim of this program is stated as:



 1.checking your network connection.
 2.Showing progress bar in each link clicked in webview.
 3.Uploading file through webview.

Note:
========
The connected website should have a android screen compatibility look and feel UI.

1.MainClass.java
=======================
package com.rajuandroid;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainClass extends Activity {
   
    WebView webview;
    ProgressDialog  progressBar;
    ProgressBar progressBar1;
    MainClass _activity;
    AlertDialog alertDialog;
    boolean loadingFinished = true;
    boolean redirect = false;
    private ValueCallback<Uri> mUploadMessage;
    private final static int FILECHOOSER_RESULTCODE = 1;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        progressBar = null;       
        this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
        _activity = this;  
        setContentView(R.layout.main );
        webview = (WebView) findViewById( R.id.webview1 );
        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(true);       
        settings.setBuiltInZoomControls(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webview.setWebChromeClient(new WebChromeClient() 
        { 
               //The undocumented magic method override 
               //Eclipse will swear at you if you try to put @Override here 
                public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg; 
                Intent i = new Intent(Intent.ACTION_GET_CONTENT); 
                i.addCategory(Intent.CATEGORY_OPENABLE); 
                i.setType("image/*"); 
                MainClass.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);           
               } 
        }); 
        if(checkInternetConnection(_activity)==true){
            if(savedInstanceState==null)               
                webview.loadUrl("http://www.xyz.com/");          
            else
                 webview.loadUrl("http://www.xyz.com/");           
            alertDialog = new AlertDialog.Builder(this).create();           
            progressBar = ProgressDialog.show(MainClass.this, "Please wait...", "Loading...");
            webview.setWebViewClient(new WebViewClient() {              
               @Override
               public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {             
               if (!loadingFinished) {
                      redirect = true;
                }   
               loadingFinished = false;
               webview.loadUrl(urlNewString);
               return true;
           }
               public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed() ;
           }
           @Override
           public void onPageFinished(WebView view, String url) {
               if(!redirect){
                  loadingFinished = true;
               }
               if(loadingFinished && !redirect){
                   //HIDE LOADING IT HAS FINISHED
                   if (progressBar != null && progressBar.isShowing()) {                     
                           progressBar.hide();
                   }
                   } else{
                  redirect = false;
                   }
            }
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {               
                super.onPageStarted(view, url, favicon);
                loadingFinished = false;
                 progressBar.show();           
            }});         
        }
        else{
            AlertDialog.Builder builder = new AlertDialog.Builder(_activity);
            builder.setMessage("Please check your network connection.")
                   .setCancelable(false)
                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                           Intent intent = new Intent(Intent.ACTION_MAIN);
                           intent.addCategory(Intent.CATEGORY_HOME);
                           intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                           startActivity(intent);
                           finish();
                       }
                   });

            AlertDialog alert = builder.create();   
            alert.show();
        }
   }
   
    public static boolean checkInternetConnection(Activity _activity) {
        ConnectivityManager conMgr = (ConnectivityManager) _activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conMgr.getActiveNetworkInfo() != null
                && conMgr.getActiveNetworkInfo().isAvailable()
                && conMgr.getActiveNetworkInfo().isConnected())
            return true;
        else
            return false;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
            Intent intent) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            Uri result = intent == null || resultCode != RESULT_OK ? null
                    : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;

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

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


3.Donot forget to add following in manifest
================================================
 <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />





14 comments:

  1. wow...thanks for this one..it works for me..

    android app developer

    ReplyDelete
  2. @amandalee23


    Thanks for reading.........

    ReplyDelete
  3. I get 2 errors :(
    1. main cannot be resolved or is not a field
    2. The public type MainClass must be defined in its own file

    ReplyDelete
    Replies
    1. Please check this
      http://stackoverflow.com/questions/5143369/main-cannot-be-resolved-or-is-not-a-field

      Delete
  4. Thanks very much.......This is a big complement for me.

    ReplyDelete
  5. Hello Rajendra,

    i found your Blog and its very interesting. since weeks i try to make my mobile website compatible with webview, but nothing seems to work. if i open my website in standard android webbrowser or in chrome browser, i can choose to uplad a picture to my site and i can choose if it come from camera or choose a file an everything is working fine. but in webview, no upload is running. your code seems to be good, opens the file chooser, but file upload don't run.
    i do not remember more, but i won't give up the project. maybe you can help me.
    if you would like to have a look at my site: http://m.hildate.de

    i would be very happy if you can help me to run the picture upload from file chooser or camera.

    ReplyDelete
  6. hi frnd can u send source code for this demo i need it pls

    ReplyDelete
    Replies
    1. Hi prabhu
      Everything is here, u can copy the code and paste in your application.

      Delete
  7. Hi Hello Sir,
    My name is Amit Bhaliya i m developing a mobile android app but i have some problem is there.the problem is that how to put hyperlink in my code so please help to me send me your email id then i will send you my code please help to me.

    Thanking You.
    Amit Bhaliya
    Android Developer

    ReplyDelete
    Replies
    1. Hi Amit
      Please send me the code to "mr.rajendranayak@gmail.com" and i will try.


      Thanks

      Delete
    2. Hi Rajendra Sir, thanks for this post. It helps me a lot. But sir could you please edit this code for downloading files from internet like pdf etc. Actully i am having an pdf file which will be donloaded but when i click on that link webwiew just refresh that page.

      Thanks once again.

      Delete
    3. Thanks a lot dear..
      Please run your code in a real device and check it again..

      Delete
  8. Not worked on my phone Android 2.3.5 for function upload file!

    ReplyDelete