Selasa, 16 April 2013

Membuat Aplikasi Posting Tweet Twitter dengan Android Menggunakan Twitter4J

Sebenarnya project Android Untuk Posting Tweet di Twitter ini sudah lama penulis buat, tetapi baru sekarang kesampaian untuk posting di Blog ini. Agak panjang langkahnya :)

Pertama download dahulu library twitter4j di url berikut. Penulis memakai twitter4j-core-android-2.2.6.jar, karena pernah bermasalah dengan versi yang lebih baru. Mungkin versi yang lebih baru cocoknya dengan Platform SDK dan Eclipse yang lebih baru pula.

Setelah itu kita daftar dahulu aplikasi di twitter dengan membuka url halaman developer twitter application ini. Setelah login dengan akun Twitter Anda, klik Create A New Application, kemudian isikan Nama dan Setting dari Aplikasi Twitter Android yang akan dibuat, misalnya seperti ini :




Setelah itu akan digenerate Aplikasi yang kita inginkan telah selesai dibuat, Copy dan simpan Twitter CONSUMER_KEY dan CONSUMER_SECRET :


Jangan lupa untuk mengubah Setting Twitter Application pada Tab Setting, ubah Setting Menjadi Read Writer :





Kemudian jalankan Eclipse, buat project baru, setelah itu tambahkan library twitter4j yang telah kita download dari Project-Properties-JavaBuild Path. Add External JAR. Atau pada Eclipse versi lebih baru bisa langsung di Copy-Paste file library JAR twitter4j ke direktori libs di project yang telah dibuat :



Buatlah desain tampilannya di /res/layout/main.xml sebagai berikut :


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    
    <!-- Twitter Login Button -->
    <Button android:id="@+id/btnLoginTwitter"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Login with Twitter"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:layout_marginTop="30dip"/>
    
    <!-- user name label -->
    <TextView android:id="@+id/lblUserName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_marginTop="30dip"/>

    <!-- label update status -->
    <TextView android:id="@+id/lblUpdate" 
        android:text="Update Status"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:visibility="gone"/>
    
    <!-- Tweet EditText -->
    <EditText android:id="@+id/txtUpdateStatus"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:visibility="gone"/>
    
    <!-- Tweet Button -->
    <Button android:id="@+id/btnUpdateStatus"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Tweet"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:visibility="gone"/>
    
    <!-- Twitter Logout button -->
    <Button android:id="@+id/btnLogoutTwitter"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Logout from Twitter"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:layout_marginTop="50dip"
        android:visibility="gone"/>

</LinearLayout>


Kemudian ketikkan kode program berikut di halaman utama src/../MainActivity.java :


package com.amijaya.androidtwitter;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

// http://cariprogram.blogspot.com
// nuramijaya@gmail.com

public class MainActivity extends Activity {
static String TWITTER_CONSUMER_KEY = "K0-ISI-DENGAN-CUNSOMER-KEY-taA"; // cosumer key 
static String TWITTER_CONSUMER_SECRET = "ssNP-ISI_DGN-CONSUMET-SECRET-2Mf1c"; // consumer secret 

static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";

static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";

static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

Button btnLoginTwitter;
Button btnUpdateStatus;
Button btnLogoutTwitter;
EditText txtUpdate;
TextView lblUpdate;
TextView lblUserName;

ProgressDialog pDialog;

private static Twitter twitter;
private static RequestToken requestToken;

private static SharedPreferences mSharedPreferences;

AlertDialogManager alert = new AlertDialogManager();

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
return;
}

btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);

mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);

btnLoginTwitter.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
loginToTwitter();
}
});

btnUpdateStatus.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
String status = txtUpdate.getText().toString();

if (status.trim().length() > 0) {
new updateTwitterStatus().execute(status);
} else {
Toast.makeText(getApplicationContext(),
"Please enter status message", Toast.LENGTH_SHORT)
.show();
}
}
});

btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
logoutFromTwitter();
}
});

if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

try {
AccessToken accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);

Editor e = mSharedPreferences.edit();

e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); 

Log.e("Twitter OAuth Token", "> " + accessToken.getToken());

btnLoginTwitter.setVisibility(View.GONE);

lblUpdate.setVisibility(View.VISIBLE);
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);

long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();

lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
} catch (Exception e) {
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
}

}

private void loginToTwitter() {
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();

TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();

try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}

class updateTwitterStatus extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}

protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);

String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");

AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

twitter4j.Status response = twitter.updateStatus(status);

Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}

protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
txtUpdate.setText("");
}
});
}

}

/** logout twitter */
private void logoutFromTwitter() {
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();

// show buttons
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);
lblUpdate.setVisibility(View.GONE);
lblUserName.setText("");
lblUserName.setVisibility(View.GONE);

btnLoginTwitter.setVisibility(View.VISIBLE);
}

/**
* Cek logged in 
* */
private boolean isTwitterLoggedInAlready() {
// twitter login status
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}

protected void onResume() {
super.onResume();
}

class AlertDialogManager {
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();

alertDialog.setTitle(title);

alertDialog.setMessage(message);

if(status != null)
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});

alertDialog.show();
}
}
}


Terakhir jangan lupa untuk memodifikasi AndroidManifest.xml agar dapat terkoneksi ke Internet :


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.amijaya.androidtwitter"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="oauth" android:host="t4jsample"/>
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

</manifest> 


Hasilnya :


Ketika diklik Login, kita harus masukkan Akun Twitter :


Setelah selesai akan otomatis redirect ke Aplikasi Twitter Android lagi :


Bisa dicoba Posting Tweet :


Selesai. Project selengkapnya dapat didownload disini : https://docs.google.com/file/d/0B4i1FYc_4RXzUjMzSU9uWTNBWEE/edit?usp=sharing. Di Google Drive klik File-Download.

Semoga menyenangkan :)