Creating a Twitter Client for Android – Tuts+ Premium
Tutorial Details
- Difficulty: Intermediate
- Completion Time: 1 Hour
It goes without saying that many people use mobile devices to connect to social media services. In this series of tutorials, we will create a basic Twitter client for the Android platform. We will use the Twitter4J library to connect to Twitter. The app will display the user’s home timeline, send tweets, retweet, and reply to tweets.
Tutorial Teaser
Step 1: Create the Database
Let’s get straight in and create the timeline database using SQLite. Create a new class in your project by selecting it in the Package Explorer, choosing File, New then Class. Enter “NiceDataHelper” as the class name. Open the new class file and extend the declaration as follows:
public class NiceDataHelper extends SQLiteOpenHelper
This is a database helper class for the SQLite system. In this class we will create and manage the database for the home timeline tweets.
Add the following import statements at the top of the class:
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import android.util.Log;
These imports are for basic database processing and error logging, plus the application Context for general reference.
The database is going to contain a single table for the tweet updates. This table will include the following columns for each tweet: the Twitter status ID; the tweet text; the screen-name of the tweeter; the time the tweet was sent; the URL of the tweeter’s profile image.
Start by creating some constants in the class:
/**db version*/ private static final int DATABASE_VERSION = 1; /**database name*/ private static final String DATABASE_NAME = "home.db"; /**ID column*/ private static final String HOME_COL = BaseColumns._ID; /**tweet text*/ private static final String UPDATE_COL = "update_text"; /**twitter screen name*/ private static final String USER_COL = "user_screen"; /**time tweeted*/ private static final String TIME_COL = "update_time"; /**user profile image*/ private static final String USER_IMG = "user_img";
These constant variables include the database version name, which you should alter if you wish to upgrade the database in future developments of your app. The variables also include the name of the database and names for the columns. The BaseColumns class helps us to assign a unique ID column using the suffix “_id”.
Next build the SQLite create table String for the home table:
/**database creation string*/
private static final String DATABASE_CREATE = "CREATE TABLE home (" + HOME_COL +
" INTEGER NOT NULL PRIMARY KEY, " + UPDATE_COL + " TEXT, " + USER_COL +
" TEXT, " + TIME_COL + " INTEGER, " + USER_IMG + " TEXT);";
Create the constructor method for your database helper class:
/**
* Constructor method
* @param context
*/
NiceDataHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
The constructor simply calls the superclass method. Next add the “onCreate” method in which we will execute creation of the database table:
/*
* onCreate executes database creation string
*/
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
Here we are simply executing the database creation SQL String. At the end of the method the table will have been created.
To finish preparing our database, implement the “onUpgrade” method in case you decide to alter the database at some future time:
/*
* onUpgrade drops home table and executes creation string
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS home");
db.execSQL("VACUUM");
onCreate(db);
}
This allows you to upgrade your database by altering the version number and creation String, or any of the columns.
We will now add a final method to our database helper class. This method is going to return values from the latest retrieved Twitter status updates and will be called from the Service class we create in the next tutorial. Add the method outline as follows:
/**
* getValues retrieves the database records
* - called from TimelineUpdater in TimelineService
* - this is a static method that can be called without an instance of the class
*
* @param status
* @return ContentValues result
*/
public static ContentValues getValues(Status status) {
//prepare ContentValues to return
ContentValues homeValues = new ContentValues();
//get the values
//return the values
return homeValues;
}
Inside this method we are going to convert the passed Status object to a set of ContentValues. The Status class is part of the Twitter4J library, modelling a single status update, or tweet. When the application Service retrieves the user’s home timeline, it will pass each of the Status updates in it to the “getValues” method. This method will retrieve the information from the tweet that we want to store in the database, i.e. the ID, text, username, time and profile image URL. The method will put each of these in a set of ContentValues which it will then return. The Service will then attempt to write the data in the ContentValues to the database, updating it with the newly retrieved tweets.
We will implement most of this process when we create the Service in the next tutorial. For now all we need to do is provide the body of the “getValues” method. Before the line in which the values are returned, add the following:
try {
//get each value from the table
homeValues.put(HOME_COL, status.getId());
homeValues.put(UPDATE_COL, status.getText());
homeValues.put(USER_COL, status.getUser().getScreenName());
homeValues.put(TIME_COL, status.getCreatedAt().getTime());
homeValues.put(USER_IMG, status.getUser().getProfileImageURL().toString());
}
catch(Exception te) { Log.e("NiceDataHelper", te.getMessage()); }
The process can cause exceptions, so the try and catch blocks are necessary. Notice that the method attempts to retrieve each element of the Status update that we designed the database to store using the Twitter4J methods. You will need another couple of imports added to the class:
import twitter4j.Status; import android.content.ContentValues;
Get the Full Series!
This tutorial series is available to Tuts+ Premium members only. Read a preview of this tutorial on the Tuts+ Premium web site or login to Tuts+ Premium to access the full content.
Joining Tuts+ Premium. . .
For those unfamiliar, the family of Tuts+ sites runs a premium membership service called Tuts+ Premium. For $19 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Mobiletuts+, Nettuts+, Aetuts+, Audiotuts+, Vectortuts+, and CgTuts+. You’ll learn from some of the best minds in the business. Become a premium member to access this tutorial, as well as hundreds of other advanced tutorials and screencasts.
