How to use Webview in ANDROID together with javascript?

By | January 19, 2011

The following java code helps you to show a webpage in ANDROID and enable javascript.

package com.pack;

import android.app.Activity;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.SumPathEffect;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnKeyListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

public class myHTML extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {

     getWindow().requestFeature(Window.FEATURE_PROGRESS);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        WebView webview = (WebView)findViewById(R.id.webview);
        TextView tv = (TextView)findViewById(R.id.tv);

        tv.setOnKeyListener(new OnKeyListener() {
 @Override
 public boolean onKey(View v, int keyCode, KeyEvent event) {

 return false;
 }
 });

        try{

             webview.getSettings().setJavaScriptEnabled(true);
        //  setContentView(webview);

              final Activity activity = this;
              webview.setWebChromeClient(new WebChromeClient() {
           public void onProgressChanged(WebView view, int progress) {
             activity.setProgress(progress * 10000);
             Toast.makeText(activity, "Loading " , Toast.LENGTH_SHORT).show();
           }
         });

              webview.setWebViewClient(new WebViewClient() {
              public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
              Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
              }
         });

         String summary = "HELLO";

         /*To load from a string use loadDataWithBaseURL  */
         webview.loadDataWithBaseURL("",summary, "text/html", "utf-8", "");

         /* To load from a file use loadUrl(remote or local) */
         //webview.loadUrl("file:///android_asset/test.html");

        }catch(Exception e){
         Toast.makeText(myHTML.this,e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }
}

3 thoughts on “How to use Webview in ANDROID together with javascript?

  1. raaj

    Hi actually i m new for android app dev. can you please tell me how to create android elements using javascript without using webview ?

    Reply

Leave a Reply to pavan Cancel reply

Your email address will not be published.