JsonActivity.java
package com.hima.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
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.JSONObject;
import android.app.Activity;
import android.os.Bundle;
public class JsonActivity extends Activity {
/** Called when the activity is first created. */
@Override
public
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String
readTwitterFeed = readTwitterFeed();
System.out.println("String="+readTwitterFeed);
try{
JSONObject
jsono=new JSONObject(readTwitterFeed);
readTwitterFeed=jsono.getString("results");
System.out.println("after
parse="+readTwitterFeed);
}
catch(Exception
e){
}
try
{
JSONArray
jsonArray = new JSONArray(readTwitterFeed);
System.out.println("Number
of entries " + jsonArray.length());
for
(int i = 0; i < jsonArray.length(); i++) {
JSONObject
jsonObject = jsonArray.getJSONObject(i);
System.out.println("text="+jsonObject.getString("text"));
System.out.println("from_user_name="+jsonObject.getString("from_user_name"));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public
String readTwitterFeed() {
StringBuilder
builder = new StringBuilder();
HttpClient
client = new DefaultHttpClient();
HttpGet
httpGet = new HttpGet("http://search.twitter.com/search.json?q=Himanshu");
try
{
HttpResponse
response = client.execute(httpGet);
StatusLine
statusLine = response.getStatusLine();
int
statusCode = statusLine.getStatusCode();
if
(statusCode == 200) {
HttpEntity
entity = response.getEntity();
InputStream
content = entity.getContent();
BufferedReader
reader = new BufferedReader(new InputStreamReader(content));
String
line;
while
((line = reader.readLine()) != null) {
builder.append(line);
}
}
else {
System.out.println(
"Failed to download file");
}
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return
builder.toString();
}
}
No comments:
Post a Comment