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 🙂

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 🙂