Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Loading a User's Twitter Timeline Using JSON

Author: Rachee Singh -- Published? true -- FormatLanguage: W

Problem:

You want to load the Twitter timeline of a user in an Android application.

Solution:

Since timeline information is public, you don't need to deal with Twitter's authentication. You can just use HttpGet to obtain the data from the user's Twitter page in JSON format. Then, the JSON can be processed to obtain the tweets by the user.

Discussion:

HttpGet is used to obtain data from the twitter page of the Times of India (a newspaper). From the response obtained after executing the request contains data from the twitter page in JSON format. We check for the status code and unless the code is 200, the request could not fetch the data. From the response we obtain the JSON and put it into the StringBuilder object. The getTwitterTimeline() method returns the String that contains the data in JSON format.

public String getTwitterTimeline() {
	StringBuilder builder = new StringBuilder();
	HttpClient client = new DefaultHttpClient();
	HttpGet httpGet = new HttpGet("http://twitter.com/statuses/user_timeline/timesofindia.json");
	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 {
			//Couldn't obtain the data
		}
	} catch (ClientProtocolException e) {
	e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return builder.toString();
	}
}

Now we process the JSON returned from the getTwitterTimeline() method in the standard way, using the getString() method. These we insert into a TextView.

String twitterTimeline = getTwitterTimeline();
	try {
		String tweets = "";
		JSONArray jsonArray = new JSONArray(twitterTimeline);
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			int j = i+1;
			tweets +="*** " + j + " ***\n";
			tweets += "Date:" + jsonObject.getString("created_at") + "\n";
			tweets += "Post:" + jsonObject.getString("text") + "\n\n";
		}
    	json= (TextView)findViewById(R.id.json);
    	json.setText(tweets);
	} catch (JSONException e) {
		e.printStackTrace();
	}

Download:

The source code for this project can be downloaded from https://docs.google.com/leaf?id=0B_rESQKgad5LZDE3MzIxNmYtMDU3Yy00OTZjLTk2NTgtMDBiNTZiYjdlYzlm&hl=en_US.
No records found.