Thursday, August 16, 2012

WebView with Example

If you want to show web application as a part of client application we can use WebView.
main.xml
<WebView android:id="@+id/webView1" android:layout_width="match_parent" android:layout_height="match_parent">
</WebView>

To open web page write.
WebView wv=(WebView)findViewById(R.id.webView1);
wv.loadUrl("http://www.google.com");

If you want to open a link url within webview.(Such as when user click of link url in webpage.It will open within webview by setting up WebViewClient)
wv.setWebViewClient(new WebViewClient());
 wv.loadUrl("http://www.google.com");
 
We can also display custom code(HTML code) in webview.if any webpage contain javascript to enable javascript in android we have to set setJavaScriptEnabled(true)
 WebSettings websetting=wv.getSettings();
        websetting.setJavaScriptEnabled(true);
        String cusdata="<html><body><h1>Hello, WebView</h1>" +
                "<input type='button' value='Say hello' />" +
"</body></html>";
 wv.loadData(cusdata, "text/html","UTF-8");


If any debug is there in webpage it will show you in logcat
(Debugging your webpage in webview)
 wv.setWebChromeClient(new WebChromeClient(){
             public void onConsoleMessage(String message,int lineno,String sourceid)
             {
                 Log.d("My Application","Messsage" + message + " line no " + lineno + " sourceid" + sourceid );
               
             }
           
         });
        
        wv.loadUrl("http://www.google.com");
Most important thing i Forget to tell you,Before doing all such thing in AndroidManifest.xml you must specify
 <uses-permission android:name="android.permission.INTERNET"/>