Failed Facebook Authorization Android SDK - android

I am trying to make a class to handle all my interactions with Facebook. I am passing the the Login activity I created to the FacebookConnector object (the object in question) to store the credentials and etc. Please view the video to see what I am dealing with http://www.youtube.com/watch?v=OkHEy9Mh1hc. Below is the FacebookConnector class with the App Id edited out
package it.stick;
import java.io.IOException;
import java.net.MalformedURLException;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class FacebookConnector {
private static final String APP_ID ="************";
private static final String[] PERMISSIONS = new String[] {"user_likes","read_stream", "user_photos", "email","photo_upload", "offline_access", "publish_actions"};
private static final String TOKEN = "access_token";
private static final String EXPIRES = "expires_in";
private static final String KEY = "facebook-credentials";
private Facebook facebook;
private Activity activity;
/** Saves applications credentials */
public boolean saveCredentials(Facebook facebook){
Editor editor = activity.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
editor.putString(TOKEN, facebook.getAccessToken());
editor.putLong(EXPIRES, facebook.getAccessExpires());
return editor.commit();
}
public boolean restoreCredentials(Facebook facebook){
SharedPreferences sharedPreferences = activity.getSharedPreferences(KEY, Context.MODE_PRIVATE);
facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
return facebook.isSessionValid();
}
public FacebookConnector(Activity activity){
facebook = new Facebook(APP_ID);
this.activity = activity;
}
// Creates new Facebook session and stores credentials
public void login(){
// 1.Restores previous credentials
//2.Creates and saves new session if previous session is not valid
restoreCredentials(facebook);
if(!facebook.isSessionValid()){
facebook.authorize(activity, PERMISSIONS, new LoginDialogListener());
}
}
public boolean isSessionValid() {
return facebook.isSessionValid();
}
public void logout(){
try {
facebook.logout(activity.getApplicationContext());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void postToWall(String message){
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
try{
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if(response == null || response.equals("") || response.equals("false")){
showToast("Blank response from facebook.");
}
else{
showToast("Message posted to your facebook wall.");
}
}
catch(Exception e){
showToast("Failed to post to wall. We fucked up :(");
e.printStackTrace();
}
}
class LoginDialogListener implements DialogListener{
#Override
public void onComplete(Bundle values) {
saveCredentials(facebook);
postToWall("logged on to Stick.it");
}
#Override
public void onFacebookError(FacebookError e) {
showToast("Authentification with Facebook failed!");
}
#Override
public void onError(DialogError e) {
showToast("Authentification with Facebook failed!");
}
#Override
public void onCancel() {
showToast("Authentification with Facebook failed!");
}
}
public void showToast(String message){
Toast.makeText(activity.getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
Here is the log cat:
02-01 22:39:39.459: W/KeyCharacterMap(637): No keyboard for id 0
02-01 22:39:39.470: W/KeyCharacterMap(637): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
02-01 22:39:46.299: D/dalvikvm(637): GC_EXPLICIT freed 91K, 50% free 2744K/5447K, external 3745K/3903K, paused 1017ms
02-01 22:39:46.999: D/webviewglue(637): nativeDestroy view: 0x303080
02-01 22:39:48.239: D/dalvikvm(637): GC_EXTERNAL_ALLOC freed 54K, 51% free 2706K/5447K, external 3331K/3903K, paused 735ms
02-01 22:39:52.139: D/Facebook-WebView(637): Webview loading URL: https://m.facebook.com/dialog/oauth?display=touch&client_id=228461823905169&scope=user_likes%2Cread_stream%2Cuser_photos%2Cemail%2Cphoto_upload%2Coffline_access%2Cpublish_actions&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess
02-01 22:40:12.209: D/Facebook-authorize(637): Login failed: com.facebook.android.DialogError: The connection to the server was unsuccessful.
02-01 22:40:12.279: D/Facebook-WebView(637): Webview loading URL: https://m.facebook.com/dialog/oauth?display=touch&client_id=228461823905169&scope=user_likes%2Cread_stream%2Cuser_photos%2Cemail%2Cphoto_upload%2Coffline_access%2Cpublish_actions&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess
02-01 22:46:14.119: W/KeyCharacterMap(637): No keyboard for id 0
02-01 22:46:14.119: W/KeyCharacterMap(637): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
I have cleared the browser cache and the app data. I have checked the key hash and I have copied and pasted the App ID multiple times into the app.

Be sure, you have added your application's signature to application setting, as:
http://developers.facebook.com/docs/mobile/android/build/#sig

Without the onActivityResult() method in the Activity you are trying to login with, the login will Facebook, because the android sdk then invokes the authorizeCallback(requestCode, resultCode, data) method.

Related

IllegalStateException in Twitter Integration

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();
}
}

onActivityResult in a non-activity class?

I am trying to implement facebook login and wall post in Android, so I created a non-activity class that handles everything. I saw all these examples where they use this method - onActivityResult but I don't know if I have to use it or why it's so important. Code works without it as long as I don't have the facebook app installed on the phone and I wonder if onActivityResult have anything to do with it. PS: I'm pretty sure I generated the hash key corectly. Thank you. :)
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.infobest.praiser.R;
import com.infobest.praiser.utils.Constants;
/**
* Functionality for facebook sharing
*
* #author oana_balaceanu
*
*/
public class ShareFacebook
{
private static final String[] PERMISSIONS = new String[] {"publish_stream"};
private Facebook facebook;
private String messageToPost;
private Context ctx;
public ShareFacebook(String messageToPost, Context ctx)
{
this.messageToPost = messageToPost;
this.ctx = ctx;
}
public boolean saveCredentials(Facebook facebook)
{
Editor editor = ctx.getSharedPreferences(Constants.KEY, Context.MODE_PRIVATE).edit();
editor.putString(Constants.TOKEN, facebook.getAccessToken());
editor.putLong(Constants.EXPIRES, facebook.getAccessExpires());
return editor.commit();
}
public boolean restoreCredentials(Facebook facebook)
{
SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.KEY,
Context.MODE_PRIVATE);
facebook.setAccessToken(sharedPreferences.getString(Constants.TOKEN, null));
facebook.setAccessExpires(sharedPreferences.getLong(Constants.EXPIRES, 0));
return facebook.isSessionValid();
}
public void share()
{
facebook = new Facebook(Constants.APP_ID);
restoreCredentials(facebook);
if (!facebook.isSessionValid())
{
loginAndPostToWall();
}
else
{
postToWall(messageToPost);
}
}
public void loginAndPostToWall()
{
facebook.authorize((Activity) ctx, PERMISSIONS,
(DialogListener) new LoginDialogListener());
}
public void postToWall(String message)
{
FacebookPoster fp = new FacebookPoster();
fp.execute(message, null, null);
}
private class FacebookPoster extends AsyncTask<String, Object, Object>
{
#Override
protected Object doInBackground(String... message)
{
Bundle parameters = new Bundle();
parameters.putString("message", message[0]);
parameters.putString("link", ctx.getResources().getString(R.string.rateLink));
parameters.putString("picture", ctx.getResources().getString(R.string.linkIconPicture));
try
{
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") || response.equals("false"))
{
return ctx.getResources().getString(R.string.facebookError);
}
else
{
return ctx.getResources().getString(R.string.facebookSuccess);
}
}
catch (Exception e)
{
Log.d("ShareOnFacebook", e.toString());
return ctx.getResources().getString(R.string.facebookError);
}
}
#Override
protected void onPostExecute(Object result)
{
super.onPostExecute(result);
showToast(result);
}
}
class LoginDialogListener implements DialogListener
{
public void onComplete(Bundle values)
{
saveCredentials(facebook);
if (messageToPost != null)
{
postToWall(messageToPost);
}
}
public void onFacebookError(FacebookError error)
{
showToast(ctx.getResources().getString(R.string.facebookError));
}
public void onError(DialogError error)
{
showToast(ctx.getResources().getString(R.string.facebookError));
}
public void onCancel()
{
showToast(ctx.getResources().getString(R.string.facebookCancel));
}
}
private void showToast(Object message)
{
Toast.makeText(ctx, message.toString(), Toast.LENGTH_SHORT).show();
}
}
If you test your app on emulator or smartphone with installed Facebook app, login will fail because of it.

POST Tweets from different Accounts in Android App

every one. I have made an application in android which post tweets on twitter, But problem is it only post tweets of my account of which I have provided "Consumer key", "Consumer secret", "oauth_token" and "oauth_token_secret".
But I want that my app should ask for login to the user( if he is not logged in already), take his tweet in editText and post to twitter. What should i do? Any help is highly appreciated.
I am using these field in my previous app.
Creating the Consumer and Access KEy web:
https://dev.twitter.com/docs/auth/tokens-devtwittercom
Consumer key xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Consumer secret xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Request token URL https://api.twitter.com/oauth/request_token
Authorize URL https://api.twitter.com/oauth/authorize
Access token URL https://api.twitter.com/oauth/access_token
Callback URL None
Access token xxxxxxxxxxxxxxxxxxxxxxxxxxxx
Access token secret xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Access level Read-only
Code:
OathRequestTokenTask.java
package com.nxb.twitter;
import com.nxb.twitter.preferences.Constants;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
/**
* An asynchronous task that communicates with Twitter to
* retrieve a request token.
* (OAuthGetRequestToken)
*
* After receiving the request token from Twitter,
* pop a browser to the user to authorize the Request Token.
* (OAuthAuthorizeToken)
*
*/
public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> {
final String TAG = getClass().getName();
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
/**
*
* We pass the OAuth consumer and provider.
*
* #param context
* Required to be able to start the intent to launch the browser.
* #param provider
* The OAuthProvider object
* #param consumer
* The OAuthConsumer object
*/
public OAuthRequestTokenTask(Context context,OAuthConsumer consumer,OAuthProvider provider) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
}
/**
*
* Retrieve the OAuth Request Token and present a browser to the user to authorize the token.
*
*/
#Override
protected Void doInBackground(Void... params) {
try {
Log.i(TAG, "Retrieving request token from Google servers");
final String url = provider.retrieveRequestToken(consumer, Constants.OAUTH_CALLBACK_URL);
Log.i(TAG, "Popping a browser with the authorize URL : " + url);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
context.startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "Error during OAUth retrieve request token", e);
}
return null;
}
}
PrepareTokenRequestActivity.java
package com.nxb.twitter;
import com.nxb.twitter.preferences.Constants;
import com.nxb.twitter.utils.TwitterUtils;
import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import android.app.Activity;
import android.content.Context;
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.preference.PreferenceManager;
import android.util.Log;
/**
* Prepares a OAuthConsumer and OAuthProvider
*
* OAuthConsumer is configured with the consumer key & consumer secret.
* OAuthProvider is configured with the 3 OAuth endpoints.
*
* Execute the OAuthRequestTokenTask to retrieve the request, and authorize the request.
*
* After the request is authorized, a callback is made here.
*
*/
public class PrepareRequestTokenActivity extends Activity {
final String TAG = getClass().getName();
private OAuthConsumer consumer;
private OAuthProvider provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
this.consumer = new CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
this.provider = new CommonsHttpOAuthProvider(Constants.REQUEST_URL,Constants.ACCESS_URL,Constants.AUTHORIZE_URL);
} catch (Exception e) {
Log.e(TAG, "Error creating consumer / provider",e);
}
Log.i(TAG, "Starting task to retrieve request token.");
new OAuthRequestTokenTask(this,consumer,provider).execute();
}
/**
* 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);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final Uri uri = intent.getData();
if (uri != null && uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) {
Log.i(TAG, "Callback received : " + uri);
Log.i(TAG, "Retrieving Access Token");
new RetrieveAccessTokenTask(this,consumer,provider,prefs).execute(uri);
finish();
}
}
public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
private SharedPreferences prefs;
public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,OAuthProvider provider, SharedPreferences prefs) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
this.prefs=prefs;
}
/**
* Retrieve the oauth_verifier, and store the oauth and oauth_token_secret
* for future API calls.
*/
#Override
protected Void doInBackground(Uri...params) {
final Uri uri = params[0];
final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
try {
provider.retrieveAccessToken(consumer, oauth_verifier);
final Editor edit = prefs.edit();
edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
edit.commit();
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
consumer.setTokenWithSecret(token, secret);
context.startActivity(new Intent(context,TwitterIntegrationActivity.class));
executeAfterAccessTokenRetrieval();
Log.i(TAG, "OAuth - Access Token Retrieved");
} catch (Exception e) {
Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
}
return null;
}
private void executeAfterAccessTokenRetrieval() {
String msg = getIntent().getExtras().getString("tweet_msg");
try {
TwitterUtils.sendTweet(prefs, msg);
} catch (Exception e) {
Log.e(TAG, "OAuth - Error sending to Twitter", e);
}
}
}
}
TwitterIntegrationActivity.java
package com.nxb.twitter;
import java.util.Date;
import oauth.signpost.OAuth;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.nxb.twitter.utils.TwitterUtils;
public class TwitterIntegrationActivity extends Activity {
private SharedPreferences prefs;
private final Handler mTwitterHandler = new Handler();
private TextView loginStatus;
private EditText status;
final Runnable mUpdateTwitterNotification = new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), "Tweet sent !", Toast.LENGTH_LONG).show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
loginStatus = (TextView)findViewById(R.id.login_status);
status=(EditText)findViewById(R.id.textStatus);
Button tweet = (Button) findViewById(R.id.btn_tweet);
Button clearCredentials = (Button) findViewById(R.id.btn_clear_credentials);
tweet.setOnClickListener(new View.OnClickListener() {
/**
* Send a tweet. If the user hasn't authenticated to Tweeter yet, he'll be redirected via a browser
* to the twitter login page. Once the user authenticated, he'll authorize the Android application to send
* tweets on the users behalf.
*/
public void onClick(View v) {
if (TwitterUtils.isAuthenticated(prefs)) {
sendTweet();
} else {
Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
i.putExtra("tweet_msg",getTweetMsg());
startActivity(i);
}
}
});
clearCredentials.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
clearCredentials();
updateLoginStatus();
}
});
}
#Override
protected void onResume() {
super.onResume();
updateLoginStatus();
}
public void updateLoginStatus() {
loginStatus.setText("Logged into Twitter : " + TwitterUtils.isAuthenticated(prefs));
}
private String getTweetMsg() {
return status.getText().toString().trim()+" "+ new Date().toLocaleString();
}
public void sendTweet() {
Thread t = new Thread() {
public void run() {
try {
TwitterUtils.sendTweet(prefs,getTweetMsg());
mTwitterHandler.post(mUpdateTwitterNotification);
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
t.start();
}
private void clearCredentials() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final Editor edit = prefs.edit();
edit.remove(OAuth.OAUTH_TOKEN);
edit.remove(OAuth.OAUTH_TOKEN_SECRET);
edit.commit();
}
}
Constants.java
package com.nxb.twitter.preferences;
public class Constants {
public static final String CONSUMER_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String CONSUMER_SECRET ="XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String OATH_TOKEN="4XXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String OATH_TOKEN_SECRET="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String REQUEST_URL = "http://api.twitter.com/oauth/request_token";
public static final String ACCESS_URL = "http://api.twitter.com/oauth/access_token";
public static final String AUTHORIZE_URL = "http://api.twitter.com/oauth/authorize";
public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-twitter";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME
+ "://" + OAUTH_CALLBACK_HOST;
}
TwitterUtils.java
package com.nxb.twitter.utils;
import com.nxb.twitter.preferences.Constants;
import oauth.signpost.OAuth;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import android.content.SharedPreferences;
public class TwitterUtils {
public static boolean isAuthenticated(SharedPreferences prefs) {
// String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
// String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
String token =Constants.OATH_TOKEN;
String secret =Constants.OATH_TOKEN_SECRET;
AccessToken a = new AccessToken(token,secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
try {
twitter.getAccountSettings();
return true;
} catch (TwitterException e) {
return false;
}
}
public static void sendTweet(SharedPreferences prefs,String msg) throws Exception {
// String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
// String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
String token =Constants.OATH_TOKEN;
String secret =Constants.OATH_TOKEN_SECRET;
AccessToken a = new AccessToken(token,secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
twitter.updateStatus(msg);
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background"
android:gravity="center_horizontal"
android:orientation="vertical" >
<TextView
android:id="#+id/login_status"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/labeleWhatisHappening"
android:textSize="30sp" />
<EditText
android:id="#+id/textStatus"
android:layout_width="fill_parent"
android:layout_height="100dip"
android:layout_margin="5dip"
android:background="#color/transparentBlue"
android:hint="#string/hintStatus"
android:marqueeRepeatLimit="marquee_forever"
android:maxLength="160"
android:maxLines="4"
android:padding="5dip"
android:textColor="#E6E6E6"
android:textColorHint="#E6E6E6" >
</EditText>
<Button
android:id="#+id/btn_tweet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tweet" />
<Button
android:id="#+id/btn_clear_credentials"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Credentials" />
</LinearLayout>

How to retrieve a twitter user's name using Twitter 4j

I'm new to android development (and java in general). I'm building an application that requires a user to signup by logging-in to their twitter account from where their basic information is imported and saved. The information required would be birthday, name (full names), username, location, sex, etc.
I'm using twitter4j to accomplish this. I've tried looking at the twitter4j documentation but being an android newbie (and java in general), the documentation is a little bit hard to understand so I seem to be unable to get it to do something other than set a status update.
This is the code in my activity:
package cc.co.localsquare.app;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
public class ConnectTwitterActivity extends BaseActivity {
public final static String CONSUMER_KEY = "valid key";
public final static String CONSUMER_SECRET = "valid secret";
public final static String CALLBACK_URL = "localsquare://ConnectTwitterActivity2";
private CommonsHttpOAuthConsumer commonHttpOAuthConsumer;
private OAuthProvider authProvider;
private Twitter twitter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connect_twitter);
commonHttpOAuthConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
authProvider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
"http://twitter.com/oauth/access_token", "http://twitter.com/oauth/authorize");
try {
String oAuthURL = authProvider.retrieveRequestToken(commonHttpOAuthConsumer, CALLBACK_URL);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(oAuthURL)));
} catch (OAuthMessageSignerException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (OAuthCommunicationException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Uri uri = intent.getData();
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
try {
authProvider.retrieveAccessToken(commonHttpOAuthConsumer, verifier);
AccessToken accessToken = new AccessToken(commonHttpOAuthConsumer.getToken(),
commonHttpOAuthConsumer.getTokenSecret());
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(accessToken);
// Alternate way:
// twitter = new TwitterFactory().getOAuthAuthorizedInstance(CONSUMER_KEY, CONSUMER_SECRET,
// new AccessToken(commonHttpOAuthConsumer.getToken(), commonHttpOAuthConsumer.getTokenSecret()));
// Tweet message to be updated.
String tweet = "Hi there, This was sent from my application - OAuth, Twitter";
twitter.updateStatus(tweet);
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG);
}
}
}
}
How EXACTLY can I solve my problem?
If you have the screen name of the twitter user for whom you need to get the details, then you can use User user = twitter.showUser(screenName);.Now you can access the information about the user by using getter functions on the object user, e.g. user.getName(), user.getLocation() etc.
Remember to import the User class in Eclipse. Generally you can also do it by pressing Ctrl+Shift+O in Eclipse.
Get the twitter object from the session once the login in complete. That can be used in the following way to extract the name
Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
long userID = twitter.getId();
twitter4j.User newUser=twitter.showUser(twitter.getScreenName());
String name=newUser.getName();
You can explore several methods from User class to get different attributes of user like profile image, friendlistlength etc
#Vineet Bhatia
Use twitter.showUser() method to get user details. To get user's name do user.getName() Remember javadoc is your friend.

Can't authorize my app using twitter4j

I'm writing an Android twitter app using twitter4j 2.2.4, and I'm having trouble getting past OAuth.
here's my code :
package info.mahmoudhossam.twitter;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.auth.AccessToken;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class TwitterActivity extends Activity {
private static int OAUTH_REQUEST = 1;
private static String consumerKey = "##########";
private static String consumerSecret = "################";
private Twitter twitter;
private AccessToken accessToken;
private TwitterBackend backend;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button loginButton = (Button) findViewById(R.id.button1);
registerForContextMenu(loginButton);
backend = new TwitterBackend();
twitter = backend.getTwitterInstance(consumerKey, consumerSecret);
}
public void onLogin(View view) {
Intent intent = new Intent("mahmoud.browser");
try {
Log.i("URL", backend.getRequestToken().getAuthenticationURL());
intent.putExtra("url", backend.getRequestToken().getAuthenticationURL());
} catch (TwitterException e) {
Log.e("Twitter", e.getMessage());
return;
}
startActivityForResult(intent, OAUTH_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == OAUTH_REQUEST && resultCode == RESULT_OK) {
Uri url = Uri.parse(data.getExtras().getString("url"));
String verifier = url.getQueryParameter("oauth_verifier");
Log.i("Verifier", verifier);
try {
accessToken = backend.getAccessToken(verifier);
} catch (TwitterException e) {
Log.e("Twitter", "Exception occurred, quitting");
return;
}
twitter.setOAuthAccessToken(accessToken);
try {
if(twitter.verifyCredentials() != null){
Toast.makeText(getApplicationContext(), "Logged in!", Toast.LENGTH_SHORT);
}
} catch (TwitterException e) {
Log.e("Twitter", e.getMessage());
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this,
"Cannot connect to twitter, app not authorized",
Toast.LENGTH_SHORT).show();
}
}
}
And the TwitterBackend class :
package info.mahmoudhossam.twitter;
import java.util.List;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
public class TwitterBackend {
private static Twitter twitter;
public Twitter getTwitterInstance(String consumerKey,
String consumerSecret){
if(twitter == null){
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(consumerKey, consumerSecret);
}
return twitter;
}
public RequestToken getRequestToken()
throws TwitterException {
return twitter.getOAuthRequestToken();
}
public AccessToken getAccessToken(String verifier)
throws TwitterException{
return twitter.getOAuthAccessToken(getRequestToken(), verifier);
}
public List<Status> getTimeline() throws TwitterException{
return twitter.getHomeTimeline();
}
public void updateStatus(String status) throws TwitterException{
twitter.updateStatus(status);
}
}
I'm getting a 401 error from twitter saying that authentication credentials are missing or incorrect, and I'm sure I've entered the correct consumer key/secret.
Is there something wrong with the code itself?
I realize this is an old question, but I used your TwitterBackend class and I had the same issue. I resolved this by making one minor change (can't say why it works, yours should have been fine).
Change this
public AccessToken getAccessToken(String verifier) throws TwitterException{
return twitter.getOAuthAccessToken(getRequestToken(), verifier);
}
To this
public AccessToken getAccessToken(String verifier) throws TwitterException{
return twitter.getOAuthAccessToken(verifier);
}
I'm unable to explain why, but I just started going down each method listed at twitter4j for getOAuthAccessToken() and got one that works.
I hope this helps someone, but thank you for the nice base class to work with.
I don't think this is a problem with your code. This is a problem with the whole Twitter authorisation mechanism, it seems that if your are logged in from the Twitter App on your phone, into Twitter then the OAuth authorization gives you this error. I guess it takes the credentials used by the Twitter App and tries to acces the App using them, and that's why you get the "incorrect credentials" message.
You can try to logout from the Twitter App of your phone, and then try again with OAuth. It worked for me, but I still couldn't find how to solve the problem when you are logged into the Twitter App and you also try to log in from your app using OAuth.
In case someone gets stuck with this, I found a solution to my problem.
It was the emulator's clock being out of sync, starting emulators from snapshots used to mess up the clock.
So if you have this problem, check the emulator's time and date, and if it's out of sync, correct it.

Categories

Resources