Web View POC Example In Android Programming

Description:
This example will show you how to use web view in 4.2 version.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it WebViewPOCExample.

2.) Write following into layout/webview.xml:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- start header bar -->

<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="vertical">
<include android:id="@+id/header" layout="@layout/header">
</include>

<!-- end of header -->
<WebView
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbarStyle="outsideOverlay"
android:scrollbarFadeDuration="5"
android:fillViewport="true"/>
</LinearLayout>
</LinearLayout>

 

 

3.) Write following into header.xml:

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content">

<!--
Start of Header layout
-->
<RelativeLayout android:id="@+id/default_header_layout"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<ImageButton
android:id="@+id/header_center_logo"
android:background="@drawable/header_logo_selector"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/header_logo"></ImageButton>
<TextView
android:text="TextView"
android:drawableTop="@drawable/header_bar_home"
android:textSize="1px"
android:layout_width="wrap_content"
android:focusable="true"
android:id="@+id/header_logo"
android:layout_height="wrap_content"></TextView>
<ImageButton android:id="@+id/header_search"

android:layout_width="wrap_content" android:layout_height="wrap_content"
android:background="@drawable/header_search_selector"
android:layout_alignParentRight="true" />
</RelativeLayout>

</RelativeLayout>

 

4.) Write following into your manifest file:

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.webview"
android:versionCode="1"
android:versionName="1.0">

<uses-permission android:name="android.permission.INTERNET" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".FirstWebView"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>
</manifest>

 

 

5.) Create and write following into ConnectionManager.java:

 

package com.example.webview;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class ConnectionManager {

private String TAG = "ConnectionManager :";
private HttpClient mHttpClient = null;
private static final int CONNECTION_TIMEOUT = 30000;

public ConnectionManager() {
/* try {*/
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 8080));

HttpParams params = new BasicHttpParams();

/* Set the timeout in milliseconds until a connection is established */

HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, CONNECTION_TIMEOUT);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

ClientConnectionManager conman = new ThreadSafeClientConnManager(params, registry);

HttpClient mHttpClient = new DefaultHttpClient(conman, params);
/* ((AbstractHttpClient) mHttpClient).setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {

* (non-Javadoc)
* @see org.apache.http.conn
* .ConnectionKeepAliveStrategy#getKeepAliveDuration(org.apache.http.HttpResponse,
* org.apache.http.protocol.HttpContext)

@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {

return 60;
}

});*/
/* } catch (CertificateException e) {
Log.e(TAG , " ConnectionManager method : " + e.getMessage());
}*/
}

public HttpClient getNewHttpClient() {

try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);

SSLSocketFactory sf = new SSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", sf, 443));
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 8080));

ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

return new DefaultHttpClient(ccm, params);
} catch (KeyStoreException ke) {
Log.e(TAG, " getNewHttpClient method : " + ke.getMessage());
return new DefaultHttpClient();
} catch (NoSuchAlgorithmException nsae) {
Log.e(TAG, " getNewHttpClient method : " + nsae.getMessage());
nsae.printStackTrace();
} catch (CertificateException ce) {
Log.e(TAG, " getNewHttpClient method : " + ce.getMessage());
ce.printStackTrace();
} catch (IOException ie) {
Log.e(TAG, " getNewHttpClient method : " + ie.getMessage());
ie.printStackTrace();
} catch (UnrecoverableKeyException ue) {
Log.e(TAG, " getNewHttpClient method : " + ue.getMessage());
ue.printStackTrace();
} catch (KeyManagementException ke) {
Log.e(TAG, " getNewHttpClient method : " + ke.getMessage());
ke.printStackTrace();
} finally {
return new DefaultHttpClient();
}
}

public JSONObject executeRequest(String url) throws IOException, JSONException, SessionExpiredException {

String strResult = null;
HttpResponse response;
JSONObject json = null;
Log.e("url ", ":" + url);
/* HttpGet httpget = new HttpGet(url);

response = mHttpClient.execute(httpget);
if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
strResult = EntityUtils.toString(entity);
Log.e("url ", ":" + url);
Log.e("response ", " : " + strResult);
json = new JSONObject(strResult);
} else {
Log.e(TAG, " executeRequest method : " );
throw new IOException();
}*/

json = new JSONObject("{"Your Nearest Store" : "Hove", "Groceries" : "You have got one to collect", " +
""Club Card Rewards": "You have 2 Goals"," +
""Direct" : "2 items on your wishlist", "Get in touch" : "http://twitter.com"}");
return json;
}

public class SessionExpiredException extends Exception {

/**
* serial version ID
*/
private static final long serialVersionUID = 3061434519353066165L;
@Override
public String getMessage() {

return "Session expired";
}

}
}

 

 

6.) Run for output.

Steps:

1.) Create a project named WebViewPOCExample and set the information as stated in the image.

Build Target: Android 4.2
Application Name: WebViewPOCExample
Package Name: com.example.WebViewPOCExample
Activity Name: WebViewPOCExample
Min SDK Version: 4.2

2.) Open FirstWebView.java file and write following code there:

 

package com.example.webview;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.webview.ConnectionManager.SessionExpiredException;

public class FirstWebView extends Activity {

private WebView mWebView;
private String TAG = "FirstWebView :";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);

ConnectionManager conMan = new ConnectionManager();

try {
JSONObject jObj = conMan.executeRequest("http://10.0.2.2:8080/RestWP/rest/hello");
Log.i(TAG, jObj.toString());
} catch (IOException ie) {
Log.e(TAG , " onCreate method : " + ie.getMessage());
ie.printStackTrace();
} catch (JSONException je) {
Log.e(TAG , " onCreate method : " + je.getMessage());
je.printStackTrace();
} catch (SessionExpiredException see) {
Log.e(TAG , " onCreate method : " + see.getMessage());
see.printStackTrace();
}

mWebView = (WebView)findViewById(R.id.webview);
mWebView.clearCache(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new JsInterface(this), "Android");
mWebView.loadUrl("http://10.0.2.2:8080/RestWP/HomePage.html");
mWebView.setWebViewClient(new FirstWebViewClient());
}

private class FirstWebViewClient extends WebViewClient {

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
/* try {
URL urlObj = new URL(url);
if (TextUtils.equals(urlObj.getHost(),"10.0.2.2")) {
return false;
} else {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
view.loadUrl(url);
return true;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
*/
return true;
}
}

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

}

private final class JsInterface {

Context mContext;

JsInterface(Context c) {
mContext = c;
}

public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}

public void launchIntent(final String app) {
//Toast.makeText(mContext, app, Toast.LENGTH_SHORT).show();
FirstWebView.this.runOnUiThread(new Runnable() {

@Override
public void run() {
Intent i = new Intent();
i.setAction("com.tesco.grocery.GROCERIES");

FirstWebView.this.startActivity(i );
}
});
}
}
}

 

 

3.) Compile and build the project.

Output

Leave a Comment:

3 comments
boost mobile android says September 28, 2013

Thanks for sharing such a nice opinion, post is pleasant, thats why i
have read it completely

Reply
AAMADI.COM says October 31, 2013

Hi,
First i like to thank you for those nice post. I like to learn about android development. But i can understand how can i do in my way. I use ADT. I like to make a apps for http://www.aamadi.com. When the apps is going to open they show a loading image and progress bar. When the apps will start they show some button as like page1, page2, page3 etc. When user click a button apps show a web page, like http://www.aamadi.com/index or http://www.aamadi.com/sound. And if the device failed to connect the internet, they show a error msg or image. Can you give me some guide line for this. I will very glad about that. Send me information about this to shanjedul@yahoo.com
Thanks in advance.

Reply
Backo says November 21, 2013

Both of the ImageButton are not used in the activity. Why?

Reply
Add Your Reply