Sie sind auf Seite 1von 5

Android Calling REST Service using AsyncTask

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

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

What are we doing in this project: 1. 2. 3. 4. Create an Activity [Start.java] with layout containing one textbox and one button When the button is clicked we will call Yahoo utility service that returns timestamp Show progress when the service is called 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. view source print? 1 // layout/main.xml 2 <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" 3 android:layout_height="fill_parent" android:layout_gravity="center|center_vertical" android:gravity="center_vertical"> <textview android:id="@+id/txtTime" android:layout_width="wrap_content" 4 android:textstyle="bold" android:textsize="15sp" android:layout_height="wrap_content" android:text="Result Here" android:layout_gravity="center_horizontal"> <button android:id="@+id/btnCallWebService" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Call REST Service" android:textsize="15sp" 5 android:layout_marginleft="100px" android:layout_marginright="100px" android:layout_marginbottom="5px" android:layout_margintop="5px" android:height="50dp" android:layout_gravity="center_horizontal"></button> 6 </textview> 7 </linearlayout> Step 5 add the click event handler in the Create of the Activity view source print? 01 // src folder/Start.java paste the code below right after setContentView 02 03 // keep the handle to the textview for later 04 this.txtTime = (TextView) findViewById(R.id.txtTime); 05 06 07 08 09 10 // 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) {

11 12 13 14 15 16 } });

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

Step 6 create a class derived from the AsyncTask and override three methods. 1. 2. 3. 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. doInBackground here is where we perform the main chunk of work. We will call Yahoo web service here. 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. 01 02 03 public class CallWebServiceTask extends AsyncTask { 04 private ProgressDialog dialog; 05 06 07 08 09 protected Context applicationContext; @Override protected void onPreExecute() { // src folder/paste the code below inside the Start activity class preferably just before the end curly brace of the Start activity class

this.dialog = ProgressDialog.show(applicationContext, "Calling", "Time Service...", true); 10 } 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 } } } @Override protected void onPostExecute(String result) { this.dialog.cancel(); String timestamp = Start.parseJSONResponse(result); timestamp = Start.UnixTimeStampToDateTime(timestamp); Start.this.getTxtTime().setText(timestamp); @Override protected String doInBackground(Void... params) { return Start.getTimeStampFromYahooService();

Here are the supporting methods from the Start activity class. view source print? 01 // src folder/Start.java paste the code below within the body of the Start.java class 02 03 04 05 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 06 java.util.Date (tiemstamp*1000)); 07 08 return dateStr;

09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

} 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.

Das könnte Ihnen auch gefallen