Android – Calling REST Service using AsyncTask

Skill Assumptions:

  1. You have configured your Android development environment on Eclipse or other tools
  2. You know how to create a new Android project

What you will learn:

  1. How to call a REST web service [based on Rest Client Class created by Luke Lowrey].
  2. How to use AsyncTask to do the work away from UI thread
  3. How to show progress dialog while we are calling the web service
  4. How to parse JSON [basic]

What are we doing in this project:

  1. Create an Activity [Start.java] with layout containing one textbox and one button
  2. When the button is clicked we will call Yahoo utility service that returns timestamp
  3. Show progress when the service is called
  4. Once the response is retrieved, parse it out and show the timestamp in human readable format

Step 1 – Create a new Eclipse project

Step 2 - Add a default Activity named Start which will add main.xml under layout folder and Start.java under your namespace folder under src.

Step 3 – Add the RestClient.java file to your src folder from the links above.

Step 4 – Add the layout for your main activity by pasting the following Xml in your layout Xml file. Basically, our layout contains two simple widgets a TextView to show the timestamp returned by the Yahoo time service.

// layout/main.xml


	
    

Step 5 – add the click event handler in the Create of the Activity

// src folder/Start.java paste the code below right after setContentView

// keep the handle to the textview for later
		this.txtTime = (TextView) findViewById(R.id.txtTime);

		// add a click event handler for the button
		final Button btnCallWebService = (Button) findViewById(R.id.btnCallWebService);
		btnCallWebService.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				CallWebServiceTask task = new CallWebServiceTask();
				task.applicationContext = Start.this;
				task.execute();
			}
		});

Step 6 – create a class derived from the AsyncTask and override three methods.

  1. onPreExecute – our opportunity to do stuff before the main chunk of work is performed within doInBackground. In our case we will show the progress dialog.
  2. doInBackground – here is where we perform the main chunk of work. We will call Yahoo web service here.
  3. onPostExecute – our opportunity to do post execution stuff here. We will dismiss the progress dialog and parse and display the timestamp in the textbox.

Here is the definition of the class derived from the AsyncTask.

// src folder/paste the code below inside the Start activity class preferably just before the end curly brace of the Start activity class

public class CallWebServiceTask extends AsyncTask {
		private ProgressDialog dialog;
		protected Context applicationContext;

		@Override
		protected void onPreExecute() {
			this.dialog = ProgressDialog.show(applicationContext, "Calling", "Time Service...", true);
		}

		@Override
		protected String doInBackground(Void... params) {

			return Start.getTimeStampFromYahooService();

		}

		@Override
		protected void onPostExecute(String result) {
			this.dialog.cancel();
			String timestamp = Start.parseJSONResponse(result);
			timestamp = Start.UnixTimeStampToDateTime(timestamp);
			Start.this.getTxtTime().setText(timestamp);
		}
	}

Here are the supporting methods from the Start activity class.

// src folder/Start.java paste the code below within the body of the Start.java class

	public static String UnixTimeStampToDateTime(String unixTimeStamp) {

		long tiemstamp = Long.parseLong(unixTimeStamp);
		String dateStr = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date (tiemstamp*1000));

		return dateStr;
	}

	public static String parseJSONResponse(String jsonResponse) {
		String timestamp = "";

		JSONObject json;
		try {
			json = new JSONObject(jsonResponse);
			JSONObject result = json.getJSONObject("Result");
			timestamp = result.getString("Timestamp");

		} catch (JSONException e) {

			e.printStackTrace();
		}

		return timestamp;
	}

	public static String getTimeStampFromYahooService() {

		String responseString = null;

		String baseurlString = "http://developer.yahooapis.com/TimeService/V1/getTime";

		RestClient client = new RestClient(baseurlString);
		client.AddParam("appid", "YahooDemo");
		client.AddParam("output", "json");

		try {
			client.Execute(RequestMethod.GET);
		} catch (Exception e) {
			e.printStackTrace();
		}

		responseString = client.getResponse();

		return responseString;
	}

Here is how your application will look when you run.



Tags: , ,

http://downloadpart.com