Hi There..
many of my friends have been looking to find a way via which they can create applications which have twitter functionality..
well m posting here a small snippet.. this snippet will be helpful for you to understand how can we make twitter work in our application..
package abhi.twitter;
/*
Copyright [2010] [Abhinava Srivastava]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import twitter4j.Twitter;
import twitter4j.http.AccessToken;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class OAuthHelp {
private static final String APPLICATION_PREFERENCES = "tweet_preferences";
private static final String TWEET_AUTH_KEY = "auth_key";
private static final String TWEET_AUTH_SEKRET_KEY = "auth_secret_key";
private SharedPreferences preferences;
private AccessToken accessToken;
private String consumerSecretKey;
private String consumerKey;
/**
* OAuthHelp class constructor loads the consumer keys
*
* @param context
*/
public OAuthHelp(Context context) {
preferences = context.getSharedPreferences(APPLICATION_PREFERENCES,
Context.MODE_PRIVATE);
loadConsumerKeys();
accessToken = loadAccessToken();
}
/**
* Depricated method has been used
*
* @param twitter
*/
@SuppressWarnings("deprecation")
public void configureOAuth(Twitter twitter) {
twitter.setOAuthConsumer(consumerKey, consumerSecretKey);
twitter.setOAuthAccessToken(accessToken);
}
/**
* true is accesstoken available false other wise
*
* @return boolean
*
*/
public boolean hasAccessToken() {
return null != accessToken;
}
/**
* Stores access token in preferences
*
* @param accessToken
*/
public void storeAccessToken(AccessToken accessToken) {
Editor editor = preferences.edit();
editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
editor.putString(TWEET_AUTH_SEKRET_KEY, accessToken.getTokenSecret());
editor.commit();
this.accessToken = accessToken;
}
/**
* Loads acess token from SharedPreferences
* @return
*/
private AccessToken loadAccessToken() {
String token = preferences.getString(TWEET_AUTH_KEY, null);
String tokenSecret = preferences.getString(TWEET_AUTH_SEKRET_KEY, null);
if (null != token && null != tokenSecret) {
return new AccessToken(token, tokenSecret);
} else {
return null;
}
}
/**
* Loads default consumer keys
*/
private void loadConsumerKeys() {
consumerKey = "tkU0PAt5vtvY169JO47Duw";
consumerSecretKey = "nYEBvt86WpyXwD84HoePW6q0gFzi4rXhhrEsZghCzlI";
}
}
package abhi.twitter;
/*
Copyright [2010] [Abhinava Srivastava]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
/**
* @author abhinava_srivastava
*/
public class TwitterApp extends Activity {
/**
* Twitter instance object
*/
private Twitter twitterConnection = null;
private OAuthHelp oHelper = null;
private RequestToken requestToken = null;
private AccessToken accessToken = null;
private WebView webView = null;
private Context context;
private Handler handleEvent = null;
private static final String CONSUMER_KEY = "tkU0PAt5vtvY169JO47Duw";
private static final String CONSUMER_SECRET = "nYEBvt86WpyXwD84HoePW6q0gFzi4rXhhrEsZghCzlI";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
handleEvent = new Handler();
twitterConnection = new TwitterFactory().getInstance();
context = this;
oHelper = new OAuthHelp(this);
}
/**
* Connects to twittter
* @param v
*/
public void getTwitter(View v) {
handleEvent.post(new Runnable() {
@Override
public void run() {
if (oHelper.hasAccessToken()) {
oHelper.configureOAuth(twitterConnection);
try {
twitterConnection.updateStatus("Hii!!!!");
} catch (TwitterException e) {
Log.d("TWEET", "Error Updating status " + e.getMessage());
e.printStackTrace();
}
} else {
try {
twitterConnection.setOAuthConsumer(CONSUMER_KEY,
CONSUMER_SECRET);
requestToken = twitterConnection
.getOAuthRequestToken("");
webViewDialog(requestToken.getAuthorizationURL(), 0);
} catch (TwitterException e) {
e.printStackTrace();
}
}
}
});
}
/**
* Shows Dialog for authentications
*
* @param authorizationURL
* @param type
*/
private void webViewDialog(final String authorizationURL, final int type) {
LinearLayout container = new LinearLayout(this);
container.setMinimumWidth(200);
container.setMinimumHeight(320);
webView = new WebView(this);
webView.setMinimumWidth(200);
webView.setMinimumHeight(380);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(authorizationURL);
container.addView(webView);
Builder webDialog = new AlertDialog.Builder(this);
webDialog.setView(container).setTitle("Web Settings")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (type == 0) {
twitterPinCodeDialog();
dialog.dismiss();
}
// dialog.dismiss();
}
}).show();
}
/**
* Pin code dialog Requests the user to enter pin shown on twitter
*/
public void twitterPinCodeDialog() {
LinearLayout pinHolder = new LinearLayout(this);
pinHolder.setGravity(Gravity.CENTER);
final EditText editPinCode = new EditText(this);
editPinCode.setGravity(Gravity.CENTER);
editPinCode.setHint("Pin Code");
editPinCode.setWidth(200);
pinHolder.addView(editPinCode);
Builder pinBuilder = new AlertDialog.Builder(this);
pinBuilder.setView(pinHolder).setTitle("Twitter Pin Code Entry")
.setMessage(
"Please enter displayed twitter code into the field")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (editPinCode.getText().toString() != null
&& !editPinCode.getText().toString().equals("")) {
try {
accessToken = twitterConnection
.getOAuthAccessToken(requestToken,
editPinCode.getText()
.toString());
oHelper.storeAccessToken(accessToken);
Log.i("Access Token:", accessToken.getToken());
Log.i("Access Secret:", accessToken
.getTokenSecret());
twitterConnection
.updateStatus("Tweeted Successfully - Abhinava Srivastava");
} catch (TwitterException te) {
if (401 == te.getStatusCode()) {
System.out
.println("Unable to get the access token.");
} else {
te.printStackTrace();
}
}
} else {
Toast.makeText(context, "Pin code is required",
Toast.LENGTH_SHORT).show();
dialog.dismiss();
twitterPinCodeDialog();
}
}
}).setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
Toast
.makeText(
context,
"To share your news please complete login next time",
Toast.LENGTH_LONG).show();
dialog.dismiss();
}
}).show();
}
}
Do not forget to add permission of INTERNET..