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 JSONBack to Android Cookbook Home | Up to Chapter: Social Networking

Author: Rachee Singh ('racheesingh')
In Published Edition? Yes
FormatLanguage: WikiFormat

Loading a User's Twitter Timeline Using JSON


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


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.


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) {
		} else {
			//Couldn't obtain the data
	} catch (ClientProtocolException e) {
	} catch (IOException e) {
	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);
	} catch (JSONException e) {

See Also