Android - Twitter Timeline Feeds Example


Today we will see how to display Twitter Timeline feeds in an android application through API calls. In this example we will fetch the recent 10 tweets posted from BBCNews Twitter account.

So let us start:

1.Create a new project File ->New -> Project ->Android ->Android Application Project. While creating the new project, name the activity as TwitterTimelineActivity(TwitterTimelineActivity .java) and layout as main.xml.

2.Now let us design the UI for the TwitterTimelineActivity i.e main.xml with a TextView within a ScrollView. Note the attribute autoLink of the TextView is set to web to display Url links.

main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >


        <TextView
            android:id="@+id/tweetTextView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:autoLink="web"
            android:background="#FFFFFF"
            android:textColor="@android:color/black" />
    </ScrollView>

</LinearLayout>
3.Now in the TwitterTimelineActivity we will call http://api.twitter.com/1/statuses/user_timeline/BBCNews.json?count=10&include_rts=1&callback=? To get the json response which will contain data like users name,id,date created text etc.. we will parse the response and fetch the date created and tweet posted and display it in the textview.To call another twitter account replace ”BBCNews” in the url with the desired account .

TwitterTimelineActivity.java
package com.twitter;

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.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class TwitterTimelineActivity extends Activity {
 TextView tweetTextView;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  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 += "Tweet #" + j + " \n";
    tweets += "Date:" + jsonObject.getString("created_at") + "\n";
    tweets += "Post:" + jsonObject.getString("text") + "\n\n";
   }
   tweetTextView = (TextView) findViewById(R.id.tweetTextView);
   tweetTextView.setText(tweets);
  } catch (JSONException e) {
   e.printStackTrace();
  }
 }

 public String getTwitterTimeline() {
  StringBuilder builder = new StringBuilder();
  HttpClient client = new DefaultHttpClient();
  HttpGet httpGet = new HttpGet(
    "http://api.twitter.com/1/statuses/user_timeline/BBCNews.json?count=10&include_rts=1&callback=?");
  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 {
    // Display couldn't obtain the data from twitter
   }
  } catch (ClientProtocolException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return builder.toString();
 }
}
4.Make the changes in AndroidManifest.xml file by including internet permission <uses-permission android:name="android.permission.INTERNET" />

5.This project is tested in android 2.2 call the url in a separate thread in android 3.0+ if a NetworkonMainThreadExecption occurs. Run the project by rightclicking project Run as → android project.

Output:

The output of this example would be similar to the one as follows: