Recipe Integrating with Twitter

Some third-party libraries exist to assist in integrating Twitter into an Android application (from http://dev.twitter.com/pages/libraries#java):

■ Twitter4J by Yusuke Yamamoto—An open-sourced, mavenized, and Google App Engine-safe Java library for the Twitter API, released under the BSD license

■ java-twitter by DeWitt Clinton—Pure Java interface for the Twitter API

■ jtwitter by Daniel Winterstein—Open-source pure Java interface to Twitter

■ Twitter Client by Gist, Inc.—-Java client to connect to the streaming API

For this recipe, the Twitter4J library by Yusuke Yamamoto is used, which has documentation at http://twitter4j.org/en/javadoc/overview-summary.html.The recipe enables users to log in to Twitter and make a tweet. At the same time, it retrieves any updated tweets and displays them to the screen.

There are two screens to specify: the login screen and update status screen (see Figure 8.2).Also on the update status screen under the EditText box, the latest status from the user account is displayed. The two activities (one for each screen) and Internet permissions need to be declared in the AndroidManifest XML file, as shown in Listing 8.7.

twiittercookbook password password

Android Meetup SV

'Tether" releases public beta (Windows only): The company 'Tether has released the public beta for the Android ve... http://blt.ly/92jflq

Android Meetup SV

Samsung Tablet runs & 1,2GHz & has Android 2.2.

As you all know by now, the device on the left is the G... http://blt.ly/bRDPpc

Android Meetup SV

"Yoirre Flredr savs SDrln

Android Meetup SV

'Tether" releases public beta (Windows only): The company 'Tether has released the public beta for the Android ve... http://blt.ly/92jflq

Android Meetup SV

Samsung Tablet runs & 1,2GHz & has Android 2.2.

As you all know by now, the device on the left is the G... http://blt.ly/bRDPpc

Android Meetup SV

"Yoirre Flredr savs SDrln

Figure 8.2 The login (left) and tweets (right) from the Twitter recipe.

Listing 8.7 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.cookbook.twitter" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon"

android:label="@string/app_name"> <activity android:name=".TwitterCookBook"

android:label="@string/app_name"> <intent-filter>

<action android:name="android.intent.action. MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>

<activity android:name=".UpdateAndList" />

</application>

<uses-permission android:name="android.permission.INTERNET"/>

</manifest>

The layout files needed are

■ login.xml—The login screen, as shown in Listing 8.8

■ main.xml—The screen to update the status and display the home status, as shown in Listing 8.9

■ usertimelinerow.xml—The view for display of each status timeline, as shown in Listing 8.10

Listing 8.8 res/layout/login.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent"

android:layout_height="fill_parent" >

<TextView android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="username"

<EditText android:id="@+id/userText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:singleLine="true"

<TextView android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="password"

<EditText android:id="@+id/passwordText"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:password="true"

android:singleLine="true"

<Button android:id="@+id/loginButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="login"

android:textSize="20dp"

</LinearLayout>

Listing 8.9 res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/twitter"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="What is in your mind?" />

<EditText android:id="@+id/userStatus" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/updateButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="update" android:textSize="20dp" />

<ListView android:layout_width="fill_parent" android:dividerHeight="1px" android:layout_height="fill_parent" android:id="list" />

</LinearLayout>

Listing 8.10 res/layout/usertimelinerow.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_alignLeft="@+id/name" android:layout_below="@+id/name"

xmlns:android="http://schemas.android.com/apk/res/android" android:padding="12dip">

<TextView android:layout_width="wrap_content"

android:layout_height="wrap_content" android:id="@+id/name" android:layout_marginRight="4dp" android:text="Diary Title " android:textStyle="bold" android:textSize="16dip" /> <TextView android:id="@+id/msg"

android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Date Recorded" android:textSize="14dip" /> </LinearLayout>

The two activities needed are the login to Twitter activity and the update and list tweets activity. The login activity is shown in Listing 8.11. It contains an EditText object for username and password, Button object to submit the login data, SharedPreferences object to save the login information upon initial successful login, and Twitter object from the twitter4j library.

Upon startup, the application checks for login information from SharedPreferences and if available, it prepopulates the EditText boxes.When the user clicks on the Button, it initiates the Twitter object with the username and password from the EditText boxes. After the Twitter object is initiated, it tries to call getFollowersIDs() to verify if the login is valid. If the login is invalid, an exception is thrown, and in this example, it shows a Toast message for login failure.

Listing 8.11 src/com/cookbook/twitter/TwitterCookBook.java package com.cookbook.twitter;

import twitter4j.Twitter; import twitter4j.TwitterFactory;

import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle;

import android.preference.PreferenceManager;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

public class TwitterCookBook extends Activity { SharedPreferences myprefs; EditText userET, passwordET; Button loginBT;

static Twitter twitter;

^Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

myprefs = PreferenceManager.getDefaultSharedPreferences(this);

final String username = myprefs.getString("username", null);

final String password = myprefs.getString("password", null);

setContentView(R.layout.login);

userET = (EditText)findViewById(R.id.userText);

passwordET = (EditText)findViewById(R.id.passwordText);

loginBT = (Button)findViewById(R.id.loginButton);

userET.setText(username);

passwordET.setText(password);

loginBT.setOnClickListener(new OnClickListener() { public void onClick(View v) { try {

twitter = new TwitterFactory()

.getInstance(userET.getText().toString(), passwordET.getText().toString()); twitter.getFollowersIDs();

Intent i = new Intent(TwitterCookBook.this, UpdateAndList.class);

startActivity(i);

Editor ed = myprefs.edit();

ed.putString("username",userET.getText().toString()); ed.putString("password", passwordET.getText().toString());

} catch (Exception e) { e.printStackTrace();

Toast.makeText(TwitterCookBook.this, "login failed!!", Toast.LENGTH_SHORT).show();

After the login is passed, the UpdateAndList activity is started.As shown in Listing 8.12, it contains an EditText object for the user to enter their tweet, a Button object to submit the tweet to the Twitter server, a Twitter object from the twitter4j library, a ResponseList of status for holding the data returned from the Twitter object, and a custom adapter for managing the status data.

The activity calls the getHomeTimeline() to retrieve the timeline status shown on the Twitter home page when a user logs in. Note that all Internet access function calls are placed inside an AsyncTask to avoid hanging the UI thread.The getHomeTimeline() method is called every time the user submits a tweet and updates the data adapter.

To hold status data in a ListView format, the activity is extended as ListActivity. Inside the ListActivity, a custom BaseAdapter called UserTimeLineAdapter is defined.This adapter uses ResponseList<Status> userTimeLine to display the data in ListView.

The ListActivity has two AsyncTask classes: setup and loadstatus.They both call the same operation getHomeTimeLine() .The only difference is that setup tries to initiate the adapter and set the ListActivity with UserTimeLineAdapter, whereas loadstatus just notifies the UserTimeLineAdapter that data is changed.

Listing 8.12 src/com/cookbook/twitter/UpdateAndList.java package com.cookbook.twitter;

import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.Twitter;

import android.app.ListActivity;

import android.content.Context;

import android.os.AsyncTask;

import android.os.Bundle;

import android.util.Log;

import android.view.Layoutlnflater;

import android.view.View;

import android.view.ViewGroup;

import android.view.View.OnClickListener;

import android.widget.BaseAdapter;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

public class UpdateAndList extends ListActivity { EditText userET; Button updateBT; Twitter twitter;

ResponseList<Status> userTimeline; UserTimeLineAdapter myAdapter;

^Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

userET = (EditText)findViewById(R.id.userStatus);

updateBT = (Button)findViewById(R.id.updateButton);

twitter = TwitterCookBook.twitter; setup stup = new setup(); stup.execute();

updateBT.setOnClickListener(new OnClickListener() { public void onClick(View v) { try {

twitter.updateStatus(userET.getText().toString());

loadstatus ldstatus = new loadstatus(); ldstatus.execute(); userET.setText(""); } catch (Exception e) { e.printStackTrace();

private class UserTimeLineAdapter extends BaseAdapter{ private Layoutlnflater mInflater;

public UserTimeLineAdapter(Context context) { mInflater = Layoutlnflater.from(context);

@Override public int getCount() {

return userTimeline.size();

@Override public Status getItem(int i) { return userTimeline.get(i);

@Override public long getItemId(int i) { return i;

@Override public View getView(int arg0, View argl, ViewGroup arg2) { final ViewHolder holder; View v = argl;

v = mInflater.inflate(R.layout.usertimelinerow, null); holder = new ViewHolder();

holder.mName = (TextView)v.findViewById(R.id.name); holder.mStatus = (TextView)v.findViewById(R.id.msg); v.setTag(holder);

holder.status= getItem(argO);

holder.mName.setText(holder.status.getUser().getName()); holder.mStatus.setText(holder.status.getText());

v.setTag(holder);

return v;

public class ViewHolder { Status status; TextView mName; TextView mStatus;

private class setup extends AsyncTask<String, Integer, String> { protected String doInBackground(String... searchKey) { try{

userTimeline = twitter.getHomeTimeline();

return ""; }catch(Exception e){

Log.v("Exception Twitter query",

"Exception:"+e.getMessage()); return "";

protected void onPostExecute(String result) { try {

myAdapter = new UserTimeLineAdapter(UpdateAndList.this); UpdateAndList.this.setListAdapter(myAdapter);

Log.v("Exception Twitter query",

"Exception:"+e.getMessage());

private class loadstatus extends AsyncTask<String, Integer, String> { protected String doInBackground(String... searchKey) { try {

userTimeline = twitter.getHomeTimeline();

Log.v("Exception Twitter query",

"Exception:"+e.getMessage()); return "";

protected void onPostExecute(String result) { try {

myAdapter.notifyDataSetChanged();

Log.v("Exception twitter query",

"Exception:"+e.getMessage());

This page intentionally left blank

Tweet Tastic Marketing

Tweet Tastic Marketing

Social media marketing is probably the number one method of marketing for businesses today, and Twitter is a major player in that. In fact its one of the best social media platforms you can use to market your business.

Get My Free Ebook


Responses

Post a comment