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 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s