Android App Development: How to Handle Your Twitter Application’s Main Activity

By Barry Burd

There are several stages to developing a Twitter app that will function on Android devices. One thing you will need to address is the application’s main activity. The following code contains the Twitter app’s Java code.

package com.allmycode.twitter;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.util.List;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
public class MainActivity extends Activity {
TextView textViewCountChars, textViewTimeline;
EditText editTextTweet, editTextUsername;
Twitter twitter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextTweet =
(EditText) findViewById(R.id.editTextTweet);
editTextTweet.addTextChangedListener
(new MyTextWatcher());
textViewCountChars =
(TextView) findViewById(R.id.textViewCountChars);
editTextUsername =
(EditText) findViewById(R.id.editTextUsername);
textViewTimeline =
(TextView) findViewById(R.id.textViewTimeline);
textViewTimeline.setMovementMethod
(new ScrollingMovementMethod());
ConfigurationBuilder builder =
new ConfigurationBuilder();
builder
.setOAuthConsumerKey(“01qedaqsdtdemrVJIkU1dg”)
.setOAuthConsumerSecret(“TudeMgXgh37Ivq173SNWnRIhI”)
.setOAuthAccessToken(“1385541-ueSEFeFgJ8vUpfy6LBv6”)
.setOAuthAccessTokenSecret(“G2FXeXYLSHI7XlVdMsS2e”);
TwitterFactory factory =
new TwitterFactory(builder.build());
twitter = factory.getInstance();
}
// Button click listeners
public void onTweetButtonClick(View view) {
new MyAsyncTaskTweet().execute
(editTextTweet.getText().toString());
}
public void onTimelineButtonClick(View view) {
new MyAsyncTaskTimeline().execute
(editTextUsername.getText().toString());
}
// Count characters in the Tweet field
class MyTextWatcher implements TextWatcher {
@Override
public void afterTextChanged(Editable s) {
textViewCountChars.setText
(““ + editTextTweet.getText().length());
}
@Override
public void beforeTextChanged
(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged
(CharSequence s, int start, int before, int count) {
}
}
// The AsyncTask classes
public class MyAsyncTaskTweet
extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String… tweet) {
String result = ““;
try {
twitter.updateStatus(tweet[0]);
result =
getResources().getString(R.string.success);
} catch (TwitterException twitterException) {
result = getResources().
getString(R.string.twitter_failure);
} catch (Exception e) {
result = getResources().
getString(R.string.general_failure);
}
return result;
}
@Override
protected void onPostExecute(String result) {
editTextTweet.setHint(result);
editTextTweet.setText(““);
}
}
public class MyAsyncTaskTimeline
extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String… username) {
String result = new String(““);
List<twitter4j.Status> statuses = null;
try {
statuses = twitter.getUserTimeline(username[0]);
} catch (TwitterException twitterException) {
result = getResources().
getString(R.string.twitter_failure);
} catch (Exception e) {
result = getResources().
getString(R.string.general_failure);
}
for (twitter4j.Status status : statuses) {
result += status.getText();
result += “n”;
}
return result;
}
@Override
protected void onPostExecute(String result) {
editTextUsername.setText(““);
textViewTimeline.setText(result);
}
}
}

Twitter’s network protocols require that the device that runs most apps is set to the correct time. This could possibly cause you lots of trouble running the app on emulators. If you face this issue, the error message that comes back from Twitter (usually specifying a null authentication challenge) isn’t helpful. So you can avoid lots of hassle by avoiding emulators whenever you test this code. Just set your phone or tablet to get the network time automatically. Then run the app on that device.

When you run the app, you see two areas. One area contains a Tweet button; the other area contains a Timeline button.

The main activity in its pristine state.

The main activity in its pristine state.

In this image, the text in both text fields is light gray. This happens because android:hint attributes are used in the code. A hint is a bunch of characters that appear only when a text field is otherwise empty. When the user clicks inside the text field, or types any text inside the text field, the hint disappears.

Type a tweet into the text field on top; then press the Tweet button.

The user types a tweet.

The user types a tweet.

If your attempt to tweet is successful, the message Success! replaces the tweet in the text field.

The app indicates a successful tweet.

The app indicates a successful tweet.

If, for one reason or another, your tweet can’t be posted, a message such as “Failed to tweet” replaces the tweet in the text field.

The app brings bad tidings to the user.

The app brings bad tidings to the user.

Next, type a username in the lower text field and click Timeline. If all goes well, a list of the user’s most recent tweets appears below the Timeline button. You can scroll the list to see more of the user’s tweets.

A user’s timeline.

A user’s timeline.