IllegalStateException in Twitter Integration - android

I am trying to integrate twitter in Android and following Twitter4j library. I have given the right consumer key and secret and have added the needed lines in manifest. Have added the Callback_URL in twitter. At first, I was able to login successfully but later it started throwing IllegalStateExcetpion.
MainActivity.java :
package com.example.feb_1twitterintegration;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
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.ProgressDialog;
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.os.StrictMode;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
static String TWITTER_CONSUMER_KEY = "XXXXXX";
static String TWITTER_CONSUMER_SECRET = "XXXXXX";
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";
ProgressDialog pDialog;
private static Twitter twitter;
private static RequestToken requestToken = new RequestToken(PREF_KEY_OAUTH_TOKEN, PREF_KEY_OAUTH_SECRET);
private static SharedPreferences mSharedPreferences;
private ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
EditText sts;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
cd = new ConnectionDetector(getApplicationContext());
if (!cd.isConnectingToInternet()) {
alert.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
return;
}
// Check if twitter keys are set
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;
}
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
findViewById(R.id.login).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
loginToTwitter();
}
});
findViewById(R.id.tweet).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
sts = (EditText) findViewById(R.id.editText1);
String status = sts.getText().toString();
if (status.trim().length() > 0) {
new updateTwitterStatus().execute(status);
} else {
Toast.makeText(getApplicationContext(),
"Please enter status message",
Toast.LENGTH_SHORT).show();
}
}
});
if (!isTwitterLoggedInAlready()) {
final String verifier;
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
//verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
System.out.println(verifier);
try {
System.out.println("Request token: "+requestToken.getAuthenticationURL());
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
System.out.println("after login");
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken);
System.out.println(accessToken.getToken());
// Shared Preferences
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());
findViewById(R.id.login).setVisibility(View.GONE);
findViewById(R.id.editText1).setVisibility(View.VISIBLE);
findViewById(R.id.tweet).setVisibility(View.VISIBLE);
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
Log.e("UserID: ", "userID: " + userID + "" + username);
Log.v("Welcome:",
"Thanks:"
+ Html.fromHtml("<b>Welcome " + username
+ "</b>"));
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), 1000)
.show();
Log.e("Twitter Login Error", "> " + e.getMessage());
e.printStackTrace();
}
}
}
}
private void loginToTwitter() {
if (!isTwitterLoggedInAlready()) {
new Thread() {
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
builder.setUseSSL(true);
builder.setApplicationOnlyAuthEnabled(true);
/*configurationBuilder.setOAuth2TokenType(getOAuth2Token().getTokenType());
configurationBuilder.setOAuth2AccessToken(getOAuth2Token().getAccessToken());*/
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter4j.Twitter twitter = factory.getInstance();
try {
System.out.println("Request token: "+requestToken.getAuthenticationURL());
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
System.out.println("Req Token: "+requestToken);
MainActivity.this.startActivity(new Intent(
Intent.ACTION_VIEW, Uri.parse(requestToken
.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
}
}.start();
} else {
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
private boolean isTwitterLoggedInAlready() {
System.out.println("Request Token in already logged in twitter: "+requestToken);
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
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);
// Access Token
String access_token = mSharedPreferences.getString(
PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
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);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
sts.setText("");
}
});
}
}
}
Logcat :
02-03 14:01:54.407: D/Network(21178): NETWORKnAME: WIFI
02-03 14:01:54.407: I/System.out(21178): Request Token in already logged in twitter: OAuthToken{token='oauth_token', tokenSecret='oauth_token_secret', secretKeySpec=null}
02-03 14:01:54.447: D/libEGL(21178): loaded /system/lib/egl/libGLES_android.so
02-03 14:01:54.467: D/libEGL(21178): loaded /system/lib/egl/libEGL_adreno200.so
02-03 14:01:54.487: D/libEGL(21178): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
02-03 14:01:54.487: D/libEGL(21178): loaded /system/lib/egl/libGLESv2_adreno200.so
02-03 14:01:54.567: I/Adreno200-EGLSUB(21178): <ConfigWindowMatch:2078>: Format RGBA_8888.
02-03 14:01:54.577: D/OpenGLRenderer(21178): Enabling debug mode 0
02-03 14:01:54.627: D/OpenGLRenderer(21178): has fontRender patch
02-03 14:01:54.657: D/OpenGLRenderer(21178): has fontRender patch
02-03 14:01:56.128: I/System.out(21178): Request Token in already logged in twitter: OAuthToken{token='oauth_token', tokenSecret='oauth_token_secret', secretKeySpec=null}
02-03 14:01:56.168: I/System.out(21178): Request token: https://api.twitter.com/oauth/authenticate?oauth_token=oauth_token
02-03 14:01:56.168: W/dalvikvm(21178): threadid=11: thread exiting with uncaught exception (group=0x40aa9228)
02-03 14:01:56.178: E/AndroidRuntime(21178): FATAL EXCEPTION: Thread-65119
02-03 14:01:56.178: E/AndroidRuntime(21178): java.lang.IllegalStateException: OAuth consumer key/secret combination not supplied
02-03 14:01:56.178: E/AndroidRuntime(21178): at twitter4j.TwitterBaseImpl.getOAuth(TwitterBaseImpl.java:403)
02-03 14:01:56.178: E/AndroidRuntime(21178): at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:298)
02-03 14:01:56.178: E/AndroidRuntime(21178): at com.example.feb_1twitterintegration.MainActivity$3.run(MainActivity.java:166)
02-03 14:01:58.741: D/OpenGLRenderer(21178): Flushing caches (mode 0)
02-03 14:01:58.751: D/memalloc(21178): /dev/pmem: Unmapping buffer base:0x52368000 size:3072000 offset:1536000
And the line where it implies for error is as follows :
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
Any idea on what might be causing this issue to appear suddenly. I have been working on this for the past 2 days but this error has appeared from nowhere. Any help will be highly appreciated. Thanks in advance.

Your error is pretty straighforward. Logcat tells you this:
FATAL EXCEPTION: Thread-65119
02-03 14:01:56.178: E/AndroidRuntime(21178): java.lang.IllegalStateException: OAuth consumer key/secret combination not supplied
You need to declare your Twitter twitter object as a class variable, because you are setting the consumer and secret keys only to an instance of the object, but when you are requesting the auth token, you get a new instance of it, that doesn't have the configuration for the keys set.
private static Twitter twitter;
Then use this twitter object in the private void loginToTwitter(), and replace this:
twitter4j.Twitter twitter = factory.getInstance();
with
twitter = factory.getInstance();
where your twitter object is now a class iVar.
Here is a sample from my own implementation, that should help you:
public class TwitterRequestTokenActivity extends Activity {
final String TAG = getClass().getName();
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_DENIED = "denied";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
static final String TWITTER_CALLBACK_URL = "appnameoauth://twitterLogin";
private static Twitter twitter;
private static RequestToken requestToken;
private AccessToken accessToken;
/** Progress */
ProgressDialog mProgressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
authenticate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
/**
* Called when the OAuthRequestTokenTask finishes (user has authorized the request token).
* The callback URL will be intercepted here.
*/
#Override
public void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
final Uri uri = intent.getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
//check if user did cancel the twitter auth
final String error = uri.getQueryParameter(URL_TWITTER_OAUTH_DENIED);
if (error==null)
getTwitterAccessToken(uri);
else {
// Login failed
Toast.makeText(TwitterRequestTokenActivity.this, getString(R.string.twitter_login_failed), Toast.LENGTH_LONG).show();
//user did not authenticate
finish();
}
}
else {
// Assume error: such as no connection
Toast.makeText(TwitterRequestTokenActivity.this, getString(R.string.twitter_login_failed), Toast.LENGTH_LONG).show();
finish();
}
}
/**
* Gets our token data once we obtain our accessToken from the asyncTask
*/
private void uploadToken() {
// upload data to our server
mProgressDialog = ProgressDialog.show(TwitterRequestTokenActivity.this, getString(R.string.generic_wait), getString(R.string.generic_sync), true, false);
// Getting user details from twitter
long userID = accessToken.getUserId();
//upload code to our server (irrelevant to question)
}
private void getTwitterAccessToken(Uri uri) {
mProgressDialog = ProgressDialog.show(TwitterRequestTokenActivity.this, getString(R.string.generic_wait), getString(R.string.twitter_logging_in), true, false);
final String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
// get the Token from Twitter
AsyncTask<Void, Void, Void> tokenTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
TwitterRequestTokenActivity.this.accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
hideProgress();
if (TwitterRequestTokenActivity.this.accessToken==null){
hideProgress();
finish();
}
else
uploadToken();
}
};
tokenTask.execute();
}
/**
* Starts the oAuth request with our callback URL
*/
private void authenticate() {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(Global.TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(Global.TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_FROM_BACKGROUND);
TwitterRequestTokenActivity.this.startActivity(intent);
}
catch (Exception e) {
finish();
}
}
});
thread.start();
}
/**
* Hides the progress bar
*/
private void hideProgress() {
try {
mProgressDialog.dismiss();
} catch (Exception e) {}
}
}
Also you need to make sure this activity is declared in your manifest as single task and set to listen to your custom oAUTH callback url:
<activity
android:name=".twitter.TwitterRequestTokenActivity"
android:configChanges="keyboardHidden|orientation"
android:launchMode="singleTask" >
<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:host="twitterLogin"
android:scheme="appnameoauth" />
</intent-filter>
</activity>

I fixed that same issue. its blocking on your ui. u just try it in asynctask. u just call that code inside a asynctask.
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
or
like this,
class TwitterLogin extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... params)
{
// TODO Auto-generated method stub
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);
// Shared Preferences
Editor e = loginPrefs.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());
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
Log.e("UserID: ", "userID: "+userID+""+username);
Log.v("Welcome:","Thanks:"+Html.fromHtml("<b>Welcome " + username + "</b>"));
}
catch (Exception e)
{
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
return null;
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
}
}

Related

Tweet Multiple Pictures Android

Twitter recently released an update allowing users to attach up to four images to a tweet. I was wondering how to implement this in an Android application.
I've found a post that was made BEFORE Twitter released the update called "Posting multiple photos in a single tweet" (I'm not showing the link because I'm only allowed to show two links with less than 10 reputation).
Now, here is the Twitter API documentation describing how to attach multiple images to a tweet, the only problem is that I have no idea how to implement this in Android:
https://dev.twitter.com/docs/api/1.1/post/statuses/update_with_media
So I was thinking of two possible solutions - either modify one of these methods from the Twitter4j library( https://github.com/yusuke/twitter4j/tree/master/twitter4j-media-support/src/main/java/twitter4j/media) to allow for multiple image attachments OR directly implement the Twitter API documentation.
Any ideas how to do this?
Input is greatly appreciated!
I have shared the multiple images on Twitter in android using twitter4j library,it is working fine to share multiple and single image on twitter
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.UploadedMedia;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
public class SharingActivity extends AppCompatActivity implements View.OnClickListener {
private static final String PREF_NAME = "sample_twitter_pref";
private static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
private static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
private static final String PREF_KEY_TWITTER_LOGIN = "is_twitter_loggedin";
private static final String PREF_USER_NAME = "twitter_user_name";
private static final int WEBVIEW_REQUEST_CODE = 223;
private static Twitter twitter;
private static RequestToken requestToken;
private static SharedPreferences mSharedPreferences;
private String consumerKey = null;
private String consumerSecret = null;
private String callbackUrl = null;
private String oAuthVerifier = null;
ImageView loginLayout,shareLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initTwitterConfigs();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
findViewById(R.id.twitBtnId).setOnClickListener(this);
findViewById(R.id.btn_share).setOnClickListener(this);
mSharedPreferences = getSharedPreferences(PREF_NAME, 0);
boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
if (isLoggedIn) {
loginLayout.setVisibility(View.VISIBLE);
shareLayout.setVisibility(View.GONE);
} else {
loginLayout.setVisibility(View.VISIBLE);
shareLayout.setVisibility(View.GONE);
}
}
private void saveTwitterInfo(AccessToken accessToken) {
long userID = accessToken.getUserId();
User user;
try {
user = twitter.showUser(userID);
String username = user.getName();
SharedPreferences.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.putString(PREF_USER_NAME, username);
e.commit();
} catch (TwitterException e1) {
e1.printStackTrace();
}
}
private void initTwitterConfigs() {
consumerKey = getString(R.string.twitter_consumer_key);
consumerSecret = getString(R.string.twitter_consumer_secret);
callbackUrl = getString(R.string.twitter_callback);
oAuthVerifier = getString(R.string.twitter_oauth_verifier);
}
private void loginToTwitter() {
boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
if (!isLoggedIn) {
final ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
final Configuration configuration = builder.build();
final TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter.getOAuthRequestToken(callbackUrl);
final Intent intent = new Intent(this, WebViewActivity.class);
intent.putExtra(WebViewActivity.EXTRA_URL, requestToken.getAuthenticationURL());
startActivityForResult(intent, WEBVIEW_REQUEST_CODE);
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent data) {
super.onActivityResult(requestCode, responseCode, data);
if (responseCode == Activity.RESULT_OK) {
String verifier = data.getExtras().getString(oAuthVerifier);
try {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
saveTwitterInfo(accessToken);
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
} catch (Exception e) {
Log.e("Twitter Login Failed", e.getMessage());
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.twitBtnId:
loginToTwitter();
break;
case R.id.btn_share:
new ShareImage().execute();
break;
}
}
public class ShareImage extends AsyncTask<Void,Void,String>{
#Override
protected void onPreExecute() {
//show progress here
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
return uploadMultipleImages();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//hide progress here
Toast.makeText(SharingActivity.this,""+result,Toast.LENGTH_LONG).show();
}
}
public String uploadMultipleImages() {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
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);
try {
Bitmap bmp[] = {BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view1),
BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view2),
BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view3),
BitmapFactory.decodeResource(getResources(), R.mipmap.lakeside_view4),
BitmapFactory.decodeResource(getResources(), R.mipmap.lakeside_view5)};
String dir = Environment.getExternalStorageDirectory() + File.separator + "myDirectory";
File folder = new File(dir);
if (!folder.exists())
folder.mkdirs();
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
long[] mediaIds = new long[4];
for (int i=0; i<4; i++) {
File tempFile = new File(dir,"image_file"+(i));
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
boolean isCompres = bmp[i].compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);
if (isCompres) {
UploadedMedia media = twitter.uploadMedia(tempFile);
mediaIds[i] = media.getMediaId();
tempFile.deleteOnExit();
}
}
StatusUpdate update = new StatusUpdate("test_name0");
update.setMediaIds(mediaIds);
Status status = twitter.updateStatus(update);
return "Successfully uploaded";
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to update status: " + te.getMessage());
}
} catch (Exception e){
e.printStackTrace();
}
return "not uloaded";
}
public String uploadSingleImage() {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
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);
try {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view1);
String dir = Environment.getExternalStorageDirectory() + File.separator + "myDirectory";
File folder = new File(dir);
if (!folder.exists())
folder.mkdirs();
File tempFile = new File(dir,"image_file"+(i));
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
boolean isCompres = bmp.compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
StatusUpdate update = new StatusUpdate("test_name0");
update.setMedia(tempFile);
Status status = twitter.updateStatus(update);
return "Successfully uploaded";
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to update status: " + te.getMessage());
}
} catch (Exception e){
e.printStackTrace();
}
return "not uloaded";
}
}
public class WebViewActivity extends Activity {
private WebView webView;
public static String EXTRA_URL = "extra_url";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
final String url = this.getIntent().getStringExtra(EXTRA_URL);
if (null == url) {
finish();
}
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl(url);
}
class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
String verifier = uri.getQueryParameter(getString(R.string.twitter_oauth_verifier));
Intent resultIntent = new Intent();
resultIntent.putExtra(getString(R.string.twitter_oauth_verifier), verifier);
setResult(RESULT_OK, resultIntent);
finish();
return true;
}
}
}
for running above code please download the below library and put it in your app libs folder and add it as dependency in gradle file
(1)twitter4j-core-4.0.4.jar
(2)twitter4j-media-support-4.0.4.jar
(3)twitter4j-stream-4.0.4.jar
(4)signpost-commonshttp4-1.2.1.1.jar
(5)signpost-core-1.2.1.1.jar
(6)signpost-jetty6-1.2.1.1.jar
It is working fine, hope it will help for you also

Authentication failed with twitter

I am trying to use the Twitter API to display tweets of a user, the problem is I got the following error message:
06-28 11:40:58.280: E/AndroidRuntime(3191): FATAL EXCEPTION: main
06-28 11:40:58.280: E/AndroidRuntime(3191): java.lang.IllegalStateException: Authentication credentials are missing. See http://twitter4j.org/en/configuration.html for details
06-28 11:40:58.280: E/AndroidRuntime(3191): at twitter4j.TwitterBaseImpl.ensureAuthorizationEnabled(TwitterBaseImpl.java:201)
06-28 11:40:58.280: E/AndroidRuntime(3191): at twitter4j.TwitterImpl.get(TwitterImpl.java:1941)
06-28 11:40:58.280: E/AndroidRuntime(3191): at twitter4j.TwitterImpl.getRetweets(TwitterImpl.java:209)
06-28 11:40:58.280: E/AndroidRuntime(3191): at com.androidhive.twitterconnect.MainActivity.afficherTweets(MainActivity.java:286)
06-28 11:40:58.280: E/AndroidRuntime(3191): at com.androidhive.twitterconnect.MainActivity.onClick(MainActivity.java:417)
06-28 11:40:58.280: E/AndroidRuntime(3191): at android.view.View.performClick(View.java:3620)
06-28 11:40:58.280: E/AndroidRuntime(3191): at android.view.View$PerformClick.run(View.java:14292)
06-28 11:40:58.280: E/AndroidRuntime(3191): at android.os.Handler.handleCallback(Handler.java:605)
06-28 11:40:58.280: E/AndroidRuntime(3191): at android.os.Handler.dispatchMessage(Handler.java:92)
06-28 11:40:58.280: E/AndroidRuntime(3191): at android.os.Looper.loop(Looper.java:137)
06-28 11:40:58.280: E/AndroidRuntime(3191): at android.app.ActivityThread.main(ActivityThread.java:4507)
06-28 11:40:58.280: E/AndroidRuntime(3191): at java.lang.reflect.Method.invokeNative(Native Method)
06-28 11:40:58.280: E/AndroidRuntime(3191): at java.lang.reflect.Method.invoke(Method.java:511)
06-28 11:40:58.280: E/AndroidRuntime(3191): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
06-28 11:40:58.280: E/AndroidRuntime(3191): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
06-28 11:40:58.280: E/AndroidRuntime(3191): at dalvik.system.NativeStart.main(Native Method)
And this is my code:
I changed them but in vain, this is my hole code:
package com.androidhive.twitterconnect;
import java.util.List;
import com.androidhive.twitterconnect.R;
import twitter4j.Status;
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.ProgressDialog;
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.os.StrictMode;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
// Constants
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
static String TWITTER_CONSUMER_KEY = "****************************";
static String TWITTER_CONSUMER_SECRET = "***********************************************";
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = " 281012441-vTUstoGd5NpWjoviMDS87JxyS4mjj713CfPNCsh2";
static final String PREF_KEY_OAUTH_SECRET = " 4rfd76K1ZUQ0eb3Zss2q6huAZra4TmWnrtj3dPKODectP";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "https://api.twitter.com/oauth/authorize";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "https://api.twitter.com/oauth/access_token";
// Login button
Button btnLoginTwitter;
// Update status button
Button btnUpdateStatus;
// Logout button
Button btnLogoutTwitter;
Button btnDisplayTwitter;
// EditText for update
EditText txtUpdate;
// lbl update
TextView lblUpdate;
TextView lblUserName;
// Progress dialog
ProgressDialog pDialog;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
btnDisplayTwitter = (Button) findViewById(R.id.button1);
btnDisplayTwitter.setOnClickListener(this);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
// All UI elements
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);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/**
* Twitter login button click event will call loginToTwitter() function
* */
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call login twitter function
loginToTwitter();
}
});
/**
* Button click event to Update Status, will call updateTwitterStatus()
* function
* */
btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
// Check for blank text
if (status.trim().length() > 0) {
// update status
new updateTwitterStatus().execute(status);
} else {
// EditText is empty
Toast.makeText(getApplicationContext(),
"Please enter status message", Toast.LENGTH_SHORT)
.show();
}
}
});
/**
* Button click event for logout from twitter
* */
btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call logout twitter function
logoutFromTwitter();
}
});
/** This if conditions is tested once is
* redirected from twitter page. Parse the uri to get oAuth
* Verifier
* */
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
AccessToken accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
lblUpdate.setVisibility(View.VISIBLE);
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
}
}
/**
* Function to login twitter
* */
private void loginToTwitter() {
// Check if already logged in
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 {
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
////////////////////////////////
public void displayTweets() throws TwitterException{
/*
Uri uri = getIntent().getData();
String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);*/
//Access Token
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
long userID = accessToken.getUserId();
System.out.println("==> "+userID);
try {
Twitter twitter = new TwitterFactory().getInstance();
//List<Status > statuses = twitter.getRetweets(Long.parseLong(args[0]));
List<Status> statuses = twitter.getRetweets(userID);
for (Status status : statuses) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
}
System.out.println("done.");
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to get retweets: " + te.getMessage());
System.exit(-1);
}
}
///////////////////////////////
/**
* Function to update status
* */
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
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);
// Access Token
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
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);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
txtUpdate.setText("");
}
});
}
}
/**
* Function to logout from twitter
* It will just clear the application shared preferences
* */
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
// After this take the appropriate action
// I am showing the hiding/showing buttons again
// You might not needed this code
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);
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
protected void onResume() {
super.onResume();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == btnDisplayTwitter){
try {
afficherTweets();
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
What's wrong?
Authentication credentials are missing.
You're missing credentials somewhere.
From your code, I'd say these :
**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
static String TWITTER_CONSUMER_KEY = "****************************";
static String TWITTER_CONSUMER_SECRET = "***********************************************";

android twitter integration using AsyncTask

plz help me in integrating twitter in my android app account using AsyncTask . I m following androidhive tutorial on integrating twitter account but i am getting Network on main thread exception.
Thanks in advance :D
This is the link of code
http://www.androidhive.info/2012/09/android-twitter-oauth-connect-tutorial/
and this is my MainActivity.java
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.ProgressDialog;
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;
public class MainActivity extends Activity {
// Constants
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
static String TWITTER_CONSUMER_KEY = ""; // place your cosumer key here
static String TWITTER_CONSUMER_SECRET = ""; // place your consumer secret here
// Preference Constants
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";
// Twitter oauth urls
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";
// Login button
Button btnLoginTwitter;
// Update status button
Button btnUpdateStatus;
// Logout button
Button btnLogoutTwitter;
// EditText for update
EditText txtUpdate;
// lbl update
TextView lblUpdate;
TextView lblUserName;
// Progress dialog
ProgressDialog pDialog;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
// All UI elements
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);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/**
* Twitter login button click event will call loginToTwitter() function
* */
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call login twitter function
loginToTwitter();
}
});
/**
* Button click event to Update Status, will call updateTwitterStatus()
* function
* */
btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
// Check for blank text
if (status.trim().length() > 0) {
// update status
new updateTwitterStatus().execute(status);
} else {
// EditText is empty
Toast.makeText(getApplicationContext(),
"Please enter status message", Toast.LENGTH_SHORT)
.show();
}
}
});
/**
* Button click event for logout from twitter
* */
btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call logout twitter function
logoutFromTwitter();
}
});
/** This if conditions is tested once is
* redirected from twitter page. Parse the uri to get oAuth
* Verifier
* */
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
AccessToken accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
lblUpdate.setVisibility(View.VISIBLE);
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
}
}
/**
* Function to login twitter
* */
private void loginToTwitter() {
// Check if already logged in
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 {
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
/**
* Function to update status
* */
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
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);
// Access Token
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
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);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
txtUpdate.setText("");
}
});
}
}
/**
* Function to logout from twitter
* It will just clear the application shared preferences
* */
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
// After this take the appropriate action
// I am showing the hiding/showing buttons again
// You might not needed this code
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);
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
protected void onResume() {
super.onResume();
}
}
You might got this error most probably in 4.0 device or IF the http conncetion is taking too long to respond.
if you dont know asynctask then simple solution will be
public static boolean isAuthenticated(Context context) {
new Thread() {
#Override
public void run() {
TwitterPrefrences twitterPref = new TwitterPrefrences(context);
String token = twitterPref.getTwitterAuthToken();
String secret = twitterPref.getTwitterAuthTokenSecrate();
AccessToken a = new AccessToken(token,secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.TWITT_CONSUMER_KEY,Constants.TWITT_CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
try {
twitter.getAccountSettings();
return true;
} catch (TwitterException e) {
return false;
}
}
}.start();
}

How do I post and retrieve tweets in an Android app?

I'm trying to make a Twitter app which includes posting and retrieving tweets from the user's timeline and setting it in a list view which also updates when someone tweets.
I also wish to allow the user to upload photos to Twitter.
Here's my code:
package com.example.listtweetdemo;
import java.util.ArrayList;
import java.util.List;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Status;
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 twitter4j.internal.org.json.JSONArray;
import twitter4j.internal.org.json.JSONObject;
import twitter4j.json.DataObjectFactory;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private Button twitt;
private Button read;
private Button login;
private Button logout;
private EditText edt;
private boolean man = true;
private TextView textName;
private ListView list;
List<Status> statuses = new ArrayList<Status>();
static final String consumerKey = "RVVVPnAUa8e1XXXXXXXXX";
static final String consumerSecretKey = "eCh0Bb12n9oDmcomBdfisKZIfJmChC2XXXXXXXXXXXX";
static final String prefName = "twitter_oauth";
static final String prefKeyOauthToken = "oauth_token";
static final String prefKeyOauthSecret = "oauth_token_secret";
static final String prefKeyTwitterLogin = "isTwitterLogedIn";
static final String twitterCallbackUrl = "oauth://t4jsample";
static final String urlTwitterOauth = "auth_url";
static final String urlTwitterVerify = "oauth_verifier";
static final String urlTwitterToken = "oauth_token";
static SharedPreferences pref;
private static Twitter twitter;
private static RequestToken reqToken;
private connectionDetector cd;
AlertDailogManager alert = new AlertDailogManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpIds();
cd = new connectionDetector(getApplicationContext());
if(!cd.isConnectivityToInternet())
{
alert.showAlert(MainActivity.this, "Internet Connection Error", "Please Connect to working Internet connection", false);
return;
}
if(consumerKey.trim().length() == 0 || consumerSecretKey.trim().length() == 0)
{
alert.showAlert(MainActivity.this, "Twitter Oauth Token", "Please set your Twitter oauth token first!", false);
return;
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginToTwitter();
}
});
logout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
logoutFromTwitter();
}
});
read.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Paging paging = new Paging(200); // MAX 200 IN ONE CALL. SET YOUR OWN NUMBER <= 200
try {
statuses = twitter.getHomeTimeline();
} catch (TwitterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String strInitialDataSet = DataObjectFactory.getRawJSON(statuses);
JSONArray JATweets = new JSONArray(strInitialDataSet);
for (int i = 0; i < JATweets.length(); i++) {
JSONObject JOTweets = JATweets.getJSONObject(i);
Log.e("TWEETS", JOTweets.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
/*try {
ResponseList<Status> statii = twitter.getHomeTimeline();
statusListAdapter adapter = new statusListAdapter(getApplicationContext(), statii);
setListAdapter(adapter);
Log.d("HOME TIMELINE", statii.toString());
} catch (TwitterException e) {
e.printStackTrace();
}
//list.setVisibility(View.VISIBLE);
read.setVisibility(View.GONE);*/
}
});
twitt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String status = edt.getText().toString();
if(status.trim().length() > 0)
{
new updateTwitter().execute(status);
}
}
});
if(!isTwitterLogedInAlready())
{
Uri uri = getIntent().getData();
if(uri != null && uri.toString().startsWith(twitterCallbackUrl))
{
String verify = uri.getQueryParameter(urlTwitterVerify);
try
{
AccessToken accessToken = twitter.getOAuthAccessToken(reqToken,verify);
Editor edit = pref.edit();
edit.putString(prefKeyOauthToken, accessToken.getToken());
edit.putString(prefKeyOauthSecret, accessToken.getTokenSecret());
edit.putBoolean(prefKeyTwitterLogin, true);
edit.commit();
Log.d("Twitter oauth Token", ">" + accessToken.getToken());
login.setVisibility(View.INVISIBLE);
twitt.setVisibility(View.VISIBLE);
edt.setVisibility(View.VISIBLE);
read.setVisibility(View.VISIBLE);
textName.setVisibility(View.VISIBLE);
if(man == true)
{
logout.setVisibility(View.VISIBLE);
}
long userId = accessToken.getUserId();
User user = twitter.showUser(userId);
//User user = twitter.getHomeTimeline();
Status n = user.getStatus();
String userName = user.getName();
textName.setText(userName);
}
catch(Exception e)
{
Log.d("Twitter Login Error", ">" + e.getMessage());
}
}
}
}
private void setUpIds() {
twitt = (Button)findViewById(R.id.buttTwitt);
login = (Button)findViewById(R.id.buttLogin);
read = (Button)findViewById(R.id.buttRead);
edt = (EditText)findViewById(R.id.editText1);
logout = (Button)findViewById(R.id.buttLogout);
textName = (TextView)findViewById(R.id.textName);
//list = (ListView)findViewById(R.id.listView1);
pref = getApplicationContext().getSharedPreferences("myPref", 0);
}
protected void logoutFromTwitter() {
Editor e = pref.edit();
e.remove(prefKeyOauthSecret);
e.remove(prefKeyOauthToken);
e.remove(prefKeyTwitterLogin);
e.commit();
login.setVisibility(View.VISIBLE);
logout.setVisibility(View.GONE);
twitt.setVisibility(View.GONE);
edt.setVisibility(View.GONE);
read.setVisibility(View.GONE);
textName.setVisibility(View.GONE);
}
protected void loginToTwitter() {
if(!isTwitterLogedInAlready())
{
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
builder.setJSONStoreEnabled(true);
builder.setIncludeEntitiesEnabled(true);
builder.setIncludeMyRetweetEnabled(true);
builder.setIncludeRTsEnabled(true);
Configuration config = builder.build();
TwitterFactory factory = new TwitterFactory(config);
twitter = factory.getInstance();
try{
reqToken = twitter.getOAuthRequestToken(twitterCallbackUrl);
this.startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(reqToken.getAuthenticationURL())));
}
catch(TwitterException e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(), "Already Logged In", Toast.LENGTH_LONG).show();
logout.setVisibility(View.VISIBLE);
man = false;
}
}
private boolean isTwitterLogedInAlready() {
return pref.getBoolean(prefKeyTwitterLogin, false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class updateTwitter extends AsyncTask<String , String, String>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to Twitter status..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
// Access Token
String access_token = pref.getString(prefKeyOauthToken, "");
// Access Token Secret
String access_token_secret = pref.getString(prefKeyOauthSecret, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Status update successfully", Toast.LENGTH_SHORT).show();
edt.setText("");
}
});
}
}
}
Use the new Twitter Fabric SDK for Android. Requires sign up first. If you don't want to wait to be approved for the sign up, then I recommend using the following link
https://github.com/Rockncoder/TwitterTutorial
The link above explains how to retrieve tweets. You should be able to use the above link COMBINED with the information in the link below to POST tweets!
https://dev.twitter.com/overview/documentation

I getting null wen return null access token

First, I have all configured (twitter keys, callback in the manifest, etc), then I do the call to twitter and get browser open, then I signIn in twitter and I accept the application, then the browser returns to application and try to get the response from twitter, but I get NULL as answer.
package com.example.fragmenttwitter;
import twitter4j.IDs;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends SherlockFragmentActivity {
private final int LOGIN = 1;
private final int TweetMenu = 2;
private final int Retweet = 3;
private final int FOWLOIING = 5;
private final int SETTING = 6;
private final int LOGOUT = 7;
static String TWITTER_CONSUMER_KEY = "xxx";
static String TWITTER_CONSUMER_SECRET = "yyy";
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";
static boolean isLogin;
private WebView wv;
private String Url = null;
Uri u;
ImageButton close;
Button cancel;
Button btnUpdateStatus;
EditText txtUpdate;
TextView lblUpdate;
TextView lblUserName;
ProgressDialog pDialog;
private PopupWindow Popup;
private static Twitter twitter;
private static RequestToken requestToken;
private static SharedPreferences mSharedPreferences;
private ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
/// option menu
#Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
menu.add(Menu.NONE, LOGIN, Menu.NONE, "Login").setShowAsAction(
MenuItem.SHOW_AS_ACTION_ALWAYS);
SubMenu submenu = menu.addSubMenu("Option");
submenu.add(Menu.NONE, TweetMenu, Menu.NONE, "Tweet").setShowAsAction(
MenuItem.SHOW_AS_ACTION_ALWAYS
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
submenu.add(Menu.NONE, FOWLOIING, Menu.NONE, "Following")
.setShowAsAction(
MenuItem.SHOW_AS_ACTION_ALWAYS
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
submenu.add(Menu.NONE, SETTING, Menu.NONE, "Setting").setShowAsAction(
MenuItem.SHOW_AS_ACTION_ALWAYS
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
submenu.add(Menu.NONE, LOGOUT, Menu.NONE, "Logout").setShowAsAction(
MenuItem.SHOW_AS_ACTION_ALWAYS
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case LOGIN:
if (item.getTitle().equals(("Login"))) {
loginToTwitter();
//new Login().execute();
item.setTitle("Logout");
} else {
logoutFromTwitter();
item.setTitle("Login");
}
break;
case TweetMenu:
ImageButton bt1 = (ImageButton) findViewById(R.id.imageButton1);
bt1.setVisibility(View.VISIBLE);
setContentView(R.layout.activity_main1);
Button bt_status = (Button) findViewById(R.id.btnUpdateStatus);
bt_status.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
final EditText etStaus = (EditText) findViewById(R.id.txtUpdateStatus);
String status = etStaus.getText().toString();
if (status.trim().length() > 0) {
new updateTwitterStatus().execute(status);
} else {
Toast.makeText(getApplicationContext(),
"Please enter status message",
Toast.LENGTH_SHORT).show();
}
}
});
break;
case Retweet:
String retweet = txtUpdate.getText().toString();
if (retweet.trim().length() > 0) {
Twitter twitter = new TwitterFactory().getInstance();
try {
twitter.retweetStatus(Long.parseLong(retweet));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),
"Please enter Tweet message", Toast.LENGTH_SHORT)
.show();
}
break;
case FOWLOIING:
Toast.makeText(getApplicationContext(), "Fowllowing called",
Toast.LENGTH_SHORT).show();
followingList();
break;
case SETTING:
Toast.makeText(getApplicationContext(), "setting called",
Toast.LENGTH_SHORT).show();
break;
case LOGOUT:
Toast.makeText(getApplicationContext(), "Logout called",
Toast.LENGTH_SHORT).show();
logoutFromTwitter();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (TWITTER_CONSUMER_KEY.trim().length() == 0
|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens",
"Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
FragmentManager f = getSupportFragmentManager();
TweetList tl = new TweetList();
FragmentTransaction ft = f.beginTransaction().add(R.id.Lineary2, tl);
ft.commit();
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);
// check for already login in or not
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);
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(); // save changes
} catch (Exception e) {
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
else
Toast.makeText(getBaseContext(), "not Login",Toast.LENGTH_LONG).show();
}
}
// code to login twitter
private void loginToTwitter() {
// Check if already logged in
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();
new Thread(new Runnable() {
public void run() {
try {
//requestToken = twitter
//.getOAuthRequestToken(TWITTER_CALLBACK_URL);
// twitter.setOAuthConsumer(TWITTER_CONSUMER_KEY,TWITTER_CONSUMER_SECRET);
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
MainActivity.this.startActivity(new Intent(
Intent.ACTION_VIEW, Uri.parse(requestToken
.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
}
}).start();
}
}
//update the stastus from twiiter app
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, "");
Log.i("Access Token", access_token);
Log.i("Access Token secrate", access_token_secret);
AccessToken accessToken = new AccessToken(access_token,
access_token_secret);
Log.i("Access Token", accessToken.toString());
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 from twitter app
public void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
}
private boolean isTwitterLoggedInAlready() {
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
public void onResume() {
super.onResume();
}
}

Categories

Resources