Handling SQLite Database from Android Programatically

Hi guys, first of all let me wish you all “A very Happy New Year”, i was working on a android project from couple of week ends so thought of putting it on my blog so that it can help some one and save his time.Android provides several ways to store user and application data. SQLite is one way of the way to store user data. SQLite is very light weight database which comes with Android OS. In this tutorial I’ll be discussing how to write classes to handle all SQLite operations.

Note: please follow the comments in the code carefully, this article is pretty simple
please find the below is the structure for the table.

AcctNo, Acct Holder Name, Acct Type, Bank Name, Created Date, amount

in order to hold the data between calls we can create the same old POJO classes, below is the OpeningBalance bean

/**
 * 
 */
package com.spark.android.pocketpassbook.model;

/**
 * @author Sony
 * 
 */
public class OpeningBalanceModel {

	private String acctNo;
	private String bankName;
	private String acctHdrName;
	private String acctType;
	private String openingDate;
	private String amount;

	/**
	 * @return the acctNo
	 */
	public String getAcctNo() {
		return acctNo;
	}

	/**
	 * @param acctNo
	 *            the acctNo to set
	 */
	public void setAcctNo(String acctNo) {
		this.acctNo = acctNo;
	}

	/**
	 * @return the bankName
	 */
	public String getBankName() {
		return bankName;
	}

	/**
	 * @param bankName
	 *            the bankName to set
	 */
	public void setBankName(String bankName) {
		this.bankName = bankName;
	}

	/**
	 * @return the acctHdrName
	 */
	public String getAcctHdrName() {
		return acctHdrName;
	}

	/**
	 * @param acctHdrName
	 *            the acctHdrName to set
	 */
	public void setAcctHdrName(String acctHdrName) {
		this.acctHdrName = acctHdrName;
	}

	/**
	 * @return the acctType
	 */
	public String getAcctType() {
		return acctType;
	}

	/**
	 * @param acctType
	 *            the acctType to set
	 */
	public void setAcctType(String acctType) {
		this.acctType = acctType;
	}

	/**
	 * @return the openingDate
	 */
	public String getOpeningDate() {
		return openingDate;
	}

	/**
	 * @param openingDate
	 *            the openingDate to set
	 */
	public void setOpeningDate(String openingDate) {
		this.openingDate = openingDate;
	}

	/**
	 * @return the amount
	 */
	public String getAmount() {
		return amount;
	}

	/**
	 * @param amount
	 *            the amount to set
	 */
	public void setAmount(String amount) {
		this.amount = amount;
	}

}

once we are done with the bean class, now its time to write the database class, which can directly handle the SQLite db. now in order to handle all database CRUD(Create, Read, Update and Delete) operations we need to write our own class which will extend from a super class SQLiteOpenHelper

/**
 * 
 */
package com.spark.android.pocketpassbook.dbhandlers;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.spark.android.pocketpassbook.model.OpeningBalanceModel;

/**
 * @author Sony
 * 
 */
public class DatabaseHandler extends SQLiteOpenHelper {

	// All Static variables
	// Database Version
	private static final int DATABASE_VERSION = 1;

	// Database Name
	private static final String DATABASE_NAME = "pocket_passbook";

	// opening_balance table name
	private static final String TABLE_OPENING_BALANCE = "opening_balance";

	// opening_balance table Columns names
	private static final String KEY_ID = "id";
	private static final String BANK_NAME = "bank_name";
	private static final String ACCT_HDR_NAME = "aact_hdr_name";
	private static final String ACCT_NUM = "aact_num";
	private static final String ACCT_TYPE = "aact_type";
	private static final String OPENING_DATE = "opening_date";
	private static final String AMOUNT = "amount";

	public DatabaseHandler(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	//onCreate method will be called for the first time in the application is deployed 
	@Override
	public void onCreate(SQLiteDatabase sqLiteDatabase) {

		String CREATE_OPENING_BAL_TABLE = "CREATE TABLE IF NOT EXISTS "
				+ TABLE_OPENING_BALANCE + "(" + KEY_ID
				+ " INTEGER PRIMARY KEY AUTOINCREMENT," + BANK_NAME + " TEXT,"
				+ ACCT_HDR_NAME + " TEXT," + ACCT_NUM + " TEXT," + ACCT_TYPE
				+ " TEXT," + OPENING_DATE + " TEXT" + ")";

		sqLiteDatabase.execSQL(CREATE_OPENING_BAL_TABLE);
	}

	// onUpgrade is called once there is a change in structure of the table
 	@Override
	public void onUpgrade(SQLiteDatabase sqLiteDatabase, int arg1, int arg2) {

		// Drop older table if existed
		sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_OPENING_BALANCE);

		// Create tables again
		onCreate(sqLiteDatabase);
	}

	public void deleteTable(String param) {

		SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
		if (param.equalsIgnoreCase("delete")) {
			// DELETE DATA FROM table if existed
			sqLiteDatabase.execSQL("DELETE FROM " + TABLE_OPENING_BALANCE);
			// Create tables again
			onCreate(sqLiteDatabase);
		} else if (param.equalsIgnoreCase("drop")) {
			// Drop older table if existed
			sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "
					+ TABLE_OPENING_BALANCE);
			// Create tables again
			onCreate(sqLiteDatabase);
		}

	}

	// Adding new opening balance data
	public boolean addOpeningBalance(OpeningBalanceModel openingBalanceModel) {
		boolean status;
		try {
			SQLiteDatabase db = this.getWritableDatabase();

			ContentValues values = new ContentValues();
			values.put(BANK_NAME, openingBalanceModel.getBankName());
			values.put(ACCT_HDR_NAME, openingBalanceModel.getAcctHdrName());
			values.put(ACCT_NUM, openingBalanceModel.getAcctNo());
			values.put(ACCT_TYPE, openingBalanceModel.getAcctType());
			values.put(OPENING_DATE, openingBalanceModel.getOpeningDate());
			//values.put(AMOUNT, openingBalanceModel.getAmount());

			// Inserting Row
			db.insert(TABLE_OPENING_BALANCE, null, values);
			db.close(); // Closing database connection
			status = true;
		} catch (Exception e) {
			status = false;
			e.printStackTrace();
		}
		return status;
	}

	// Getting All opening balance records
	public List<OpeningBalanceModel> getAllOpeningBalance() {
		List<OpeningBalanceModel> OpeningBalanceModelList = new ArrayList<OpeningBalanceModel>();
		// Select All Query
		String selectQuery = "SELECT  * FROM " + TABLE_OPENING_BALANCE;

		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);

		// looping through all rows and adding to list
		if (cursor.moveToFirst()) {
			do {
				OpeningBalanceModel openingBalanceModel = new OpeningBalanceModel();
				openingBalanceModel.setBankName(cursor.getString(1));
				openingBalanceModel.setAcctHdrName(cursor.getString(2));
				openingBalanceModel.setAcctNo(cursor.getString(3));
				openingBalanceModel.setAcctType(cursor.getString(4));
				openingBalanceModel.setOpeningDate(cursor.getString(5));

				// Adding contact to list
				OpeningBalanceModelList.add(openingBalanceModel);
			} while (cursor.moveToNext());
		}

		// return contact list
		return OpeningBalanceModelList;
	}

	// Getting All opening balance records
	public List<OpeningBalanceModel> getNameAndAcctType(String acctNo) {
		List<OpeningBalanceModel> OpeningBalanceModelList = new ArrayList<OpeningBalanceModel>();
		// Select All Query
		String selectQuery = "SELECT  * FROM " + TABLE_OPENING_BALANCE
				+ " WHERE " + ACCT_NUM + "=" + acctNo;

		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);

		// looping through all rows and adding to list
		if (cursor.moveToFirst()) {
			do {
				OpeningBalanceModel openingBalanceModel = new OpeningBalanceModel();
				openingBalanceModel.setBankName(cursor.getString(1));
				openingBalanceModel.setAcctHdrName(cursor.getString(2));
				openingBalanceModel.setAcctNo(cursor.getString(3));
				openingBalanceModel.setAcctType(cursor.getString(4));
				openingBalanceModel.setOpeningDate(cursor.getString(5));

				// Adding contact to list
				OpeningBalanceModelList.add(openingBalanceModel);
			} while (cursor.moveToNext());
		}

		// return contact list
		return OpeningBalanceModelList;
	}

}

in order to run this we should have a main activity and call the DatabaseHandler object from the main activity.
as shown below.


package com.spark.android.pocketpassbook.testing;

import java.util.List;
 
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
 
public class AndroidSQLiteTutorialActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         
        DatabaseHandler db = new DatabaseHandler(this);
         
        final OpeningBalanceModel openingBalanceModel = new OpeningBalanceModel();
        // all the values i got it from front end after the form gets filled. 
        // if not we can just hardcode and test it.

        final EditText bankName = (EditText) findViewById(R.id.bankName);
	final EditText acctHdrName = (EditText) findViewById(R.id.acctHdrName);
	final EditText acctNo = (EditText) findViewById(R.id.acctNo);
	final EditText acctType = (EditText) findViewById(R.id.acctType);
	final EditText openingDate = (EditText) findViewById(R.id.openingDate);

        // set the values to model object
        openingBalanceModel.setBankName(bankName.getText()
							.toString().trim());
	openingBalanceModel.setAcctHdrName(acctHdrName.getText()
							.toString().trim());
	openingBalanceModel.setAcctNo(acctNo.getText().toString()
							.trim());
	openingBalanceModel.setAcctType(acctType.getText()
							.toString().trim());
	openingBalanceModel.setOpeningDate(openingDate.getText()
							.toString().trim());
        
        // calling the database handler object by passing the model object to it
        boolean status = openingBalanceDatabaseHandler.addOpeningBalance(openingBalanceModel);
    }
    }
}

Lets meet in my next tutorial (Android Text To Speech)
Happy Coding in Android 🙂

JQuery mobile and jqPlot

Hi guys, its a long time i wrote a post, these days got little busy with work. So now this is a post to integrate jquery mobile api with the jqplot to render some grap dash boards in mobile and these garph dash bords when combined with jquery mobile are compatible with all popular OS like Android and iOS .. etc. So below is the code to do it and its very self explanatory.

Following files are to be included and then start the coding part
Proj_Exp

<html lang="html">
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>Dynamic collapsible - jQuery Mobile Demos</title>
		<link rel="stylesheet"  href="css/jquery.mobile-1.3.1.min.css">
		<link rel="stylesheet" href="css/jqm-demos.css">
		<link class="include" rel="stylesheet" type="text/css" href="jquery.jqplot.min.css" />

		<script class="include" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
		<script src="js/index.js"></script>
		<script src="js/jquery.mobile-1.3.1.min.js"></script>

		<script>
			$(document).on("pageshow", function() {
				$.jqplot.config.enablePlugins = true;
				var s1 = [2, 6, 7, 10];
				var ticks = ['a', 'b', 'c', 'd'];

				plot1 = $.jqplot('chart1', [s1], {
					// Only animate if we're not using excanvas (not in IE 7 or IE 8)..
					animate : !$.jqplot.use_excanvas,
					seriesDefaults : {
						renderer : $.jqplot.BarRenderer,
						pointLabels : {
							show : false
						}
					},
					axes : {
						xaxis : {
							renderer : $.jqplot.CategoryAxisRenderer
							//ticks : ticks
						}
					},
					highlighter : {
						show : false
					}
				});

				$('#chart1').bind('jqplotDataClick', function(ev, seriesIndex, pointIndex, data) {
					$('#info1').html('series: ' + seriesIndex + ', point: ' + pointIndex + ', data: ' + data);
				});

				var data = [['Heavy Industry', 12], ['Retail', 9], ['Light Industry', 14], ['Out of home', 16], ['Commuting', 7], ['Orientation', 9]];
				var plot1 = jQuery.jqplot('chart2', [data], {
					seriesDefaults : {
						// Make this a pie chart.
						renderer : jQuery.jqplot.PieRenderer,
						rendererOptions : {
							// Put data labels on the pie slices.
							// By default, labels show the percentage of the slice.
							showDataLabels : true
						}
					},
					legend : {
						show : false,
						location : 'e'
					}
				});
			});
		</script>
	</head>
	<body>

		<!-- Start of first page: #one -->
		<div data-role="page" id="one">

			<div data-role="header">
				<h1>Multi-page</h1>
			</div><!-- /header -->

			<div data-role="content" >
				<h2>Home Page</h2>

				<ul data-role="listview" data-inset="true" data-theme="d" data-divider-theme="e" data-count-theme="b">
					<li data-role="list-divider">
						Log Analysis Report
					</li>
					<li>
						<a href="index.html" data-theme="e">Bar Chart Analysis</a>
					</li>
					<li>
						<a href="index.html">Pie Chart Analysis</a>
					</li>
					<li>
						<a href="index.html">Line Chart Analysis</a>
					</li>
					<li>
						<a href="index.html">Combination Chart Analysis</a>
					</li>
				</ul>
				<div>
					<span>You Clicked: </span><span id="info1">Nothing yet</span>
				</div>

				<div id="chart1" style="margin-top:20px; margin-left:20px; width:300px; height:300px;"></div>

				<h3>Show internal pages:</h3>
				<p>
					<a href="#two" data-role="button" data-transition="slideup">Show Pie Report</a>
				</p>

			</div><!-- /content -->

			<div data-role="footer" data-theme="d">
				<h4>Page Footer</h4>
			</div><!-- /footer -->
		</div><!-- /page one -->

		<!-- Start of second page: #two -->
		<div data-role="page" id="two" data-theme="a">

			<div data-role="header">
				<h1>Pie Report</h1>
			</div><!-- /header -->

			<div data-role="content" data-theme="a">
				<h2>Pie Report</h2>
				<div id="chart2" style="margin-top:20px; margin-left:20px; width:300px; height:300px;"></div>
				<p>
					<a href="#one" data-direction="reverse" data-role="button" data-theme="b">Back to Home Page</a>
				</p>

			</div><!-- /content -->

			<div data-role="footer">
				<h4>Page Footer</h4>
			</div><!-- /footer -->
		</div><!-- /page two -->

		<!-- Don't touch this! -->
		<script class="include" type="text/javascript" src="js/jquery.jqplot.min.js"></script>

		<!-- Additional plugins go here -->

		<script class="include" type="text/javascript" src="js/jqplot.barRenderer.min.js"></script>
		<script class="include" type="text/javascript" src="js/jqplot.pieRenderer.min.js"></script>

		<script class="include" type="text/javascript" src="js/jqplot.categoryAxisRenderer.min.js"></script>
		<script class="include" type="text/javascript" src="js/jqplot.pointLabels.min.js"></script>

		<!-- End additional plugins -->

	</body>
</html>

and the following are the simulated output for the above code in the mobile.

first_screen

sec_screen

Happy Coding mobile apps 🙂

Android Rest Client to call Spring MVC Project – Part 2

Hi all in the previous post i have shown you how to create a mavenized Spring MVC Project with full configuration in that the Spring controller is returning a JSON String, now this is the string we want to collect in android client by calling it using Spring-Rest-Template.

The Jar files required for this application are
android-support-v4.jar
spring-android-auth-1.0.0.RELEASE.jar
spring-android-core-1.0.0.RELEASE.jar
spring-android-rest-template-1.0.0.RELEASE.jar

For JSON Support add the following jar files
jackson-core-asl-1.9.11.jar
jackson-mapper-asl-1.9.11.jar

commons-httpclient-3.1.jar is used to HttpHeader Support.

package com.example.springandroid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;

public class MainActivity extends ListActivity {

	private static String[] content = { "JavaSE", "JavaEE", "JavaME" };

	public static final int ADD_MENU = Menu.FIRST + 1;
	public static final int REFRESH_MENU = Menu.FIRST + 2;
	public static final int EDIT_MENU = Menu.FIRST + 3;
	public static final int REMOVE_MENU = Menu.FIRST + 4;

	private ArrayList<String> arrayList = null;

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

		registerForContextMenu(getListView());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(Menu.NONE, ADD_MENU, Menu.NONE, "Add Content");
		menu.add(Menu.NONE, REFRESH_MENU, Menu.NONE, "Refresh Content");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.add(Menu.NONE, EDIT_MENU, Menu.NONE, "Edit Content");
		menu.add(Menu.NONE, REMOVE_MENU, Menu.NONE, "Remove Content");
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case ADD_MENU:
			addContent();
			return true;

		case REFRESH_MENU:
			initAdapter();
			return true;

		}
		return super.onOptionsItemSelected(item);
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();

		@SuppressWarnings("rawtypes")
		ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
		switch (item.getItemId()) {
		case EDIT_MENU:
			final String item1 = arrayList.get(info.position);
			// item1 = item1.toUpperCase();
			final View addView = getLayoutInflater().inflate(
					R.layout.activity_main, null);
			final EditText name = (EditText) addView.findViewById(R.id.title);
			new AlertDialog.Builder(this)
					.setTitle("Add Content")
					.setView(addView)
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								@SuppressWarnings("unchecked")
								public void onClick(DialogInterface dialog,
										int whichButton) {
									@SuppressWarnings("rawtypes")
									ArrayAdapter adapter = (ArrayAdapter) getListAdapter();

									name.setText(item1);
									adapter.insert(name.getText().toString(),
											info.position);
								}
							}).setNegativeButton("Discard", null).show();
			adapter.remove(arrayList.get(info.position));

			return (true);
		case REMOVE_MENU:
			adapter.remove(arrayList.get(info.position));
			return (true);
		}
		return super.onContextItemSelected(item);
	}

	private Thread getUpdates = new Thread() {
		public void run() {

			String url = "http://10.40.230.54:8080/AndroidSpring/spring/retrieve";

			HttpHeaders requestHeaders = new HttpHeaders();
			requestHeaders.setContentType(new MediaType("text", "xml"));

			HttpEntity<String> requestEntity = new HttpEntity<String>(
					requestHeaders);

			RestTemplate restTemplate = new RestTemplate();
			restTemplate.getMessageConverters().add(
					new StringHttpMessageConverter());
			ResponseEntity<String> responseEntity = restTemplate.exchange(url,
					HttpMethod.POST, requestEntity, String.class);
			final String result = responseEntity.getBody();
			Log.d("Message", result); // prints the response collected from the server

			
			try {
				
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						JSONObject jsonObject;
						try {
							jsonObject = new JSONObject(result);
							Log.d("JSON is", ""+jsonObject.toString());
							
							initAdapter();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						
					}
				});

				
			} catch (Exception e) {
			}
		}
	};

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void initAdapter() {
		arrayList = new ArrayList<String>();
		Log.d("String Array Length:", "" + content.length);
		for (String contents : content) {
			arrayList.add(contents);
		}
		setListAdapter(new ArrayAdapter(this,
				android.R.layout.simple_list_item_1, arrayList));
	}

	private void addContent() {
		final View addView = getLayoutInflater().inflate(
				R.layout.activity_main, null);
		new AlertDialog.Builder(this).setTitle("Add Content").setView(addView)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@SuppressWarnings({ "rawtypes", "unchecked" })
					public void onClick(DialogInterface dialog, int whichButton) {
						ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
						EditText name = (EditText) addView
								.findViewById(R.id.title);
						adapter.add(name.getText().toString());
						
					}
				}).setNegativeButton("Discard", null).show();
	}
	
	
}

if you want to send parameters to Spring app. Please code the controller relavently i am giving the android call to Spring controller

private Thread addToDataBase = new Thread(){
		public void run(){
			String url = "http://10.40.230.54:8080/AndroidSpring/spring/insert?username={username}&password={password}";

			HttpHeaders requestHeaders = new HttpHeaders();
			requestHeaders.setContentType(new MediaType("text", "xml"));

			HttpEntity<String> requestEntity = new HttpEntity<String>(
					requestHeaders);

			RestTemplate restTemplate = new RestTemplate();
			restTemplate.getMessageConverters().add(
					new StringHttpMessageConverter());
			/*ResponseEntity<String> responseEntity = restTemplate.exchange(url,
					HttpMethod.POST, requestEntity, String.class);*/
			Map<String, Object> uriVariables = new HashMap<String, Object>();
		    uriVariables.put("username", "Administrator");
		    uriVariables.put("password", "Administrator123");

		    ResponseEntity<String> responseEntity = restTemplate.exchange(url,
					HttpMethod.POST, requestEntity, String.class,uriVariables);
			Log.d("Message", responseEntity.getBody());
		}
	};

Happy Coding 🙂

Android Rest Client to call Spring MVC Project – Part 1

Hi All, This time i had very tough time to show my proof of concept to one of my colleague regarding java Spring mvc and Android. the requirement is quite direct we have to create a Spring MVC project and deploy it to server and call the spring controller using Android Activity. Thanks to spring it has released Spring-rest-template api using which we can call the business logic that is deployed in the server as spring controller. so here is my example code to you how to call spring mvc using Android Rest Client

in this part i will be explaining u how to create a spring mvc project using maven dependencies.

Note: dont code network related logic in the main thread of android activity it will lead to android.os.NetworkOnMainThreadException

Create a mavenized Spring Project as below:
Step1: POM.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spark.android.spring</groupId>
	<artifactId>AndroidSpring</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>AndroidSpring</name>
	<description>AndroidSpring</description>

	<properties>
		<org.slf4j-version>1.6.1</org.slf4j-version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>net.sf.ezmorph</groupId>
			<artifactId>ezmorph</artifactId>
			<version>1.0.6</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.8.3</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.18</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>3.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<!-- Spring Security -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-taglibs</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-crypto</artifactId>
			<version>3.1.0.RELEASE</version>
		</dependency>

		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.6.10</version>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>

		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- Hibernate Validator -->
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.0.0.GA</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>4.2.0.CR1</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>3.4.0.GA</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>

	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>tomcat-maven-plugin</artifactId>
				<version>1.0-beta-1</version>
			</plugin>
			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>7.4.0.v20110414</version>
				<configuration></configuration>
			</plugin>
		</plugins>
		<pluginManagement>
			<plugins>
				<!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
				<plugin>
					<groupId>org.eclipse.m2e</groupId>
					<artifactId>lifecycle-mapping</artifactId>
					<version>1.0.0</version>
					<configuration>
						<lifecycleMappingMetadata>
							<pluginExecutions>
								<pluginExecution>
									<pluginExecutionFilter>
										<groupId>
											org.apache.maven.plugins
										</groupId>
										<artifactId>
											maven-compiler-plugin
										</artifactId>
										<versionRange>
											[2.3.2,)
										</versionRange>
										<goals>
											<goal>compile</goal>
											<goal>testCompile</goal>
										</goals>
									</pluginExecutionFilter>
									<action>
										<ignore></ignore>
									</action>
								</pluginExecution>
							</pluginExecutions>
						</lifecycleMappingMetadata>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
	<!-- needed for XmlSchema -->
	<repositories>
		<repository>
			<id>ibiblio</id>
			<name>ibiblio maven repository</name>
			<url>http://ibiblio.org/maven/</url>
			<layout>legacy</layout>
		</repository>
		<repository>
			<id>apache</id>
			<name>Apache maven repository</name>
			<url>http://www.apache.org/dist/java-repository/</url>
			<layout>legacy</layout>
		</repository>
	</repositories>

</project>

Step2:Place all configuration files in src/main/resources of ur maven project
code for application-context.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
			http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
			http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

	<!-- component scan for detecting @controller annotations -->
	<context:component-scan base-package="com.spark.android"></context:component-scan>
	
	<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
	<task:executor id="myExecutor" pool-size="5"/>
	<task:scheduler id="myScheduler" pool-size="10"/>
	
	<tx:annotation-driven/>
	
	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="MyPersistenceUnit" />
		<property name="dataSource" ref="dataSource" />
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="showSql" value="true" />
				<property name="generateDdl" value="false" />
				<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
			</bean>
		</property>
	</bean>
	
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url"
			value="jdbc:mysql://localhost:3306/android" />
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>
</beans>

code for controllers.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd	
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- Activates various annotations to be detected in bean classes -->	
	<context:annotation-config></context:annotation-config>

	<!-- Scans within the base package of the application for @Components to configure as beans -->
	<context:component-scan base-package="com.spark.android" />
	
	
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- one of the properties available; the maximum file size in bytes -->
		<property name="maxUploadSize" value="10000000" />
	</bean>
	
	
</beans>

code for spring-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<!-- Enables the Spring MVC @Controller programming Model -->
	<annotation-driven />

	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/" />
		<beans:property name="suffix" value=".html" />
	</beans:bean>

	<!-- Imports user-defined @Controller beans that process client requests -->
	<beans:import resource="controllers.xml" />

</beans:beans>

For database interaction i decided to make use of JPA over Hibernate, so create a folder META-INF(All caps) in your src/main/resources/ and pleace persistence.xml file in it with the following code.

persistence.xml:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
	version="2.0">
	
	<persistence-unit name="MyPersistenceUnit" transaction-type="RESOURCE_LOCAL">
	<class>com.spark.android.model.Credentials</class>
	</persistence-unit>
	
</persistence>

now that we have completed our configuration its time for us to write the model classes and business logic for handling requests from android client and return responce. Here we use JSON for communication layer. notice that you put the code in appropriate packages.
source code for controller

/**
 * 
 */
package com.spark.android.controller;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spark.android.model.Credentials;

/**
 * @author Mantha Pavan Kumar
 *
 */
@Controller
public class AndroidSpringController {

	@RequestMapping(value="/insert",method=RequestMethod.POST)
	public @ResponseBody String handleInsertRequest(){
		
		Credentials credentials = new Credentials();
		credentials.setUsername("PavanKumar");
		credentials.setPassword("pavan~123!");
		
		JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( credentials );  
		
		return jsonObject.toString();
	}
}

and following is the model class(POJO)

/**
 * 
 */
package com.spark.android.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author Mantha Pavan Kumar
 *
 */
@Entity
@Table(name="contacts")
public class Credentials implements Serializable{

	private int id;
	private String username;
	private String password;
	
	/**
	 * @return
	 */
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	public int getId() {
		return id;
	}
	/**
	 * @param id
	 */
	public void setId(int id) {
		this.id = id;
	}
	/**
	 * @return
	 */
	@Column(name="username")
	public String getUsername() {
		return username;
	}
	/**
	 * @param username
	 */
	public void setUsername(String username) {
		this.username = username;
	}
	/**
	 * @return
	 */
	@Column(name="password")
	public String getPassword() {
		return password;
	}
	/**
	 * @param password
	 */
	public void setPassword(String password) {
		this.password = password;
	}
}

once this is ready now lets start coding your web.xml file as our project is a web application. create a folder WEB-INF(all caps) in src/main/webapps/

code for web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- Defines all the spring context information for all servlets and Filters 
		that share the info -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:application-context.xml</param-value>
	</context-param>

	<!-- creates spring container listener shared by all servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- request processing servlet -->
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-context.xml</param-value>
		</init-param>
	</servlet>

	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/spring/*</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>pages/index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

now its time to test the application open cmd and navigate to the project folder and issue “mvn clean install package”
without quotes it will download all jar files needed by your application and it builds the war file(bueauty of maven)
now your project is ready for deployment issue the command “mvn tomcat:run” without quotes your tomcats starts and your war will be deployed now your Spring MVC project is up and running lets see how to code Android REST client and communicate with Spring Web App in Part-II.

Happy Coding 🙂

Calling a remote Servlet using Android Activity.

Hi all, in the past i received some queries regarding “how to call EJB from Android?”, at that time i am not sure but i just replied by saying call a servlet from your Android and its the servlet that internally calls EJB, Yes its true there is no direct implementation to call EJB from Android but we can call a servlet from Android and from there its your logic to call any business components like EJB,etc. following is my tutorial which will take you how to call Servlet from Android
Note:This tutorial will create Servlets with specification 3.0 with no web.xml and uses annotations to map the requests from client.

1.Create a dynamic web project with servlet specification 3.0 and create a servlet in src folder of your project as shown below.
2.Deploy the servlet in local server(Apache-tomcat 7.x) and test the working by hitting the below url http://localhost:8080/AndroidServlet/androidServlet

package com.spark.android.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AndroidServlet
 * @author Mantha Pavan Kumar
 */
@WebServlet("/androidServlet")
public class AndroidServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AndroidServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter printWriter = response.getWriter();
		printWriter.println("Sample Page !");
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

Now its time to create android project(using Eclipse), Assuming all the prerequisites of android are already installed in your environment lets start the project.

3.create Android Application project
4.In the main.xml file add the below content

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/button" />

    <TextView
        android:id="@+id/outputTxt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#CC0033"
        android:textSize="16sp"
        android:textStyle="bold" />

</LinearLayout>

5. in res/values/strings.xml add the below content

<resources>

    <string name="app_name">SimpleHttpGetServlet</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
	<string name="button">Invoke Servlet</string>
</resources>

6.Now in the MainActivity.java place the below content

package com.example.simplehttpgetservlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{
    Button button;
    TextView outputText;
 
    public static final String URL = "http://10.40.230.98:8080/AndroidServlet/androidServlet";
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        findViewsById();
 
        button.setOnClickListener(this);
    }
 
    private void findViewsById() {
        button = (Button) findViewById(R.id.button);
        outputText = (TextView) findViewById(R.id.outputTxt);
    }
 
    public void onClick(View view) {
        GetXMLTask task = new GetXMLTask();
        task.execute(new String[] { URL });
    }
 
    private class GetXMLTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            String output = null;
            for (String url : urls) {
                output = getOutputFromUrl(url);
            }
            return output;
        }
 
        private String getOutputFromUrl(String url) {
            String output = null;
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
 
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                output = EntityUtils.toString(httpEntity);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return output;
        }
 
        @Override
        protected void onPostExecute(String output) {
            outputText.setText(output);
        }
    }
}

7.Finally we give persmissions to our android app to access internet in the AndroidManifest.xml as below.

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

    <uses-sdk
        android:minSdkVersion="8"
        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>

Thats it launch your AVD by running the Android project and click the button, you will see the response from servlet.
Happy coding 🙂