package com.ravinder;
import java.io.IOException;
import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class CallingRestActivity extends Activity {
private ListView listView = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.listView1);
new CallServiceTask().execute();
}
class CallServiceTask extends AsyncTask<Void, Void, HttpResponse> {
@Override
protected HttpResponse doInBackground(Void... params) {
String url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=India%20Prime%20Minester";
//String url="http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=hyderabad%20population";
HttpGet get = new HttpGet(url);
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
try {
response = client.execute(get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(HttpResponse result) {
super.onPostExecute(result);
Scanner sc = null;
try {
sc = new Scanner(result.getEntity().getContent(), "UTF-8");
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
StringBuffer buffer = new StringBuffer();
while (sc.hasNext()) {
buffer.append(sc.next());
}
System.out.println("final output:" + buffer);
try {
// creating json object with string
JSONObject jsonObject = new JSONObject(buffer.toString());
// /getting the json object of responseData
JSONObject json = (JSONObject) jsonObject.get("responseData");
System.out.println("json is:" + json);
// getting the Json arrays where key is results
JSONArray array = json.getJSONArray("results");
System.out.println("arrray size is:" + array.length());
String[] results = new String[array.length()];
for (int i = 0; i < array.length(); i++) {
JSONObject object = (JSONObject) array.get(i);
results[i] = object.getString("content");
}
listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,results));
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
}
No comments:
Post a Comment