Twitter Authentication in Android - android

In my app,i want to show twitter login everytime a user tried to share a post.
I dont want to save the twitter credentials in shared preference,but when i tried to share a post in second time,it is not showing the login fields.
can anyone figure out the problem?
public class AuthorizationActivity extends Activity {
private TwitterActivity app;
private WebView webView;
static String token, verifier;
Webservice web;
OAuthCredentialsResponse credentials;
private WebViewClient webViewClient = new WebViewClient() {
#Override
public void onLoadResource(WebView view, String url) {
final OAuthHmacSigner signer = new OAuthHmacSigner();
Uri uri = Uri.parse(url);
if (url.startsWith(Constants.OAUTH_CALLBACK_URL)) {
try {
if (url.indexOf("oauth_token=")!=-1) {
token = uri.getQueryParameter("oauth_token");
verifier = uri.getQueryParameter("oauth_verifier");
signer.clientSharedSecret = Constants.CONSUMER_SECRET;
OAuthGetAccessToken accessToken = new OAuthGetAccessToken(
Constants.ACCESS_URL);
accessToken.transport = new ApacheHttpTransport();
accessToken.temporaryToken = token;
accessToken.signer = signer;
accessToken.consumerKey = Constants.CONSUMER_KEY;
accessToken.verifier = verifier;
credentials = accessToken.execute();
signer.tokenSharedSecret = credentials.tokenSecret;
+ credentials.tokenSecret);
;
if (null != token) {
webView.setVisibility(View.INVISIBLE);
finish();
} else if (url.indexOf("error=")!=-1) {
view.setVisibility(View.INVISIBLE);
}
}} catch (IOException e) {
e.printStackTrace();
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.authorization_view);
setUpViews();
String authURL = beginAuthorization();
webView.loadUrl(authURL);
}
private void setUpViews() {
webView = (WebView) findViewById(R.id.web_view);
webView.setWebViewClient(webViewClient);
}
public String beginAuthorization() {
try {
final OAuthHmacSigner signer = new OAuthHmacSigner();
OAuthAuthorizeTemporaryTokenUrl authorizeUrl;
signer.clientSharedSecret = Constants.CONSUMER_SECRET;
OAuthGetTemporaryToken temporaryToken = new OAuthGetTemporaryToken(Constants.REQUEST_URL);
temporaryToken.transport = new ApacheHttpTransport();
temporaryToken.signer = signer;
temporaryToken.consumerKey = Constants.CONSUMER_KEY;
temporaryToken.callback = Constants.OAUTH_CALLBACK_URL;
OAuthCredentialsResponse tempCredentials = temporaryToken.execute();
signer.tokenSharedSecret = tempCredentials.tokenSecret;
authorizeUrl = new OAuthAuthorizeTemporaryTokenUrl(Constants.AUTHORIZE_URL);
authorizeUrl.temporaryToken = tempCredentials.token;
String authorizationUrl = authorizeUrl.build();
System.out.println(authorizationUrl);
return authorizationUrl;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public void authorized() {
try {
AccessToken a = new AccessToken(credentials.token,credentials.tokenSecret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
twitter.updateStatus("my first post");
Toast t = Toast.makeText(this,"Successfully Shared",Toast.LENGTH_LONG);
t.show();
} catch (TwitterException e) {
throw new RuntimeException("Unable to authorize user", e);
}
}

I think you missed one parameter in the URL
that's force_login = true , This will ask user to login even the session is not expired.
To read more go to this link RestAPI

Related

Android - Tumblr Access Token via OAuth

I am trying to allow Android users to post to their Tumblr blogs using my app. I am able to launch Tumblr, enter my username and password, and log in, however the problem is the Access Token I receive appears to be invalid (I get a 401 - Unauthorized when I use it with any of Tumblr's API calls).
Below is the code I am using. I am able to authenticate with Twitter, but Tumblr is giving me difficulties. If anyone has any ideas, suggestions, or improvements, they would be much appreciated. Thanks!
public final class TumblrWebView extends Activity {
private final String TAG = getClass().getSimpleName();
OAuth10Service service;
public final static String PARAMETER_CONSUMER_KEY = "CONSUMER_KEY";
public final static String PARAMETER_CONSUMER_SECRET = "CONSUMER_SECRET";
public final static String PARAMETER_CALLBACK_URL = "CALLBACK_URL";
private String consumerKey;
private String consumerSecret;
private String callbackUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view);
/*
* Get params
*/
Intent intent = getIntent();
consumerKey = intent.getStringExtra(PARAMETER_CONSUMER_KEY);
consumerSecret = intent.getStringExtra(PARAMETER_CONSUMER_SECRET);
callbackUrl = intent.getStringExtra(PARAMETER_CALLBACK_URL);
service = OAuthService.newInstance(new TumblrApi(), consumerKey, consumerSecret, new OAuth10ServiceCallback() {
#Override
public void onOAuthAccessTokenReceived(OAuth10Token token) {
complete(token);
Log.i(TAG, "Access token recieved");
// System.out.println("token recieved " + token.getAccessToken());
// System.out.println("token recieved " + token.getUserSecret());
}
#Override
public void onOAuthRequestTokenReceived() {
loadWebView();
Log.i(TAG, "Request token recieved");
}
#Override
public void onOAuthRequestTokenFailed(HootResult result) {
Log.e(TAG, "Token request failed " + result.getException());
}
#Override
public void onOAuthAccessTokenFailed(HootResult result) {
Log.e(TAG, "Token access failed " + result);
}
});
service.start();
}
#SuppressLint("SetJavaScriptEnabled")
private void loadWebView() {
final WebView webview = (WebView) findViewById(R.id.web_view);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Checking for our successful callback
if(url.startsWith(callbackUrl)) {
webview.setVisibility(View.GONE);
Log.d(TAG, "token url " + url + " " + service.getOAuthAccessToken(url));
} else {
Log.d(TAG, "token url");
}
return super.shouldOverrideUrlLoading(view, url);
}
});
webview.loadUrl(service.getAuthorizeUrl());
}
private void complete(OAuth10Token token) {
Intent resultIntent = new Intent();
resultIntent.putExtra(TumblrUtils.PREF_TUMBLR_ACCESS, token.getAccessToken());
resultIntent.putExtra(TumblrUtils.PREF_TUMBLR_SECRET, token.getUserSecret());
setResult(RESULT_OK, resultIntent);
finish();
}
}
EDIT: A helper class
public class TumblrUtils {
// Consumer Key and Secret
private static final String TUMBLR_CONSUMER_KEY = "{ ENTER TUMBLR CONSUMER KEY }";
private static final String TUMBLR_CONSUMER_SECRET = "{ ENTER TUMBLR CONSUMER SECRET }";
// Callback URL
private static final String TUMBLR_CALLBACK_URL = "http://example.com";
// Request Code
public static final int TUMBLR_REQUEST_CODE = 87; /* 87 - TR */
// Preference Constants
public static final String PREF_TUMBLR_USER = "tumblr_user";
public static final String PREF_TUMBLR_ACCESS = "tumblr_access_token";
public static final String PREF_TUMBLR_SECRET = "tumblr_secret_token";
public static final String TUMBLR_REQUEST_URL = "http://www.tumblr.com/oauth/request_token";
public static final String TUMBLR_ACCESS_URL = "http://www.tumblr.com/oauth/access_token";
public static final String TUMBLR_AUTHORIZE_URL = "http://www.tumblr.com/oauth/authorize";
private static OAuthConsumer tumblrConsumer;
private static String tumblrHost;
private static String tumblrToken;
private static String tumblrTokenSecret;
private static String getConsumerKey() {
return TUMBLR_CONSUMER_KEY;
}
private static String getConsumerSecret() {
return TUMBLR_CONSUMER_SECRET;
}
private static String getCallbackUrl() {
return TUMBLR_CALLBACK_URL;
}
public static String getRequestUrl() {
return TUMBLR_REQUEST_URL;
}
public static String getAccessUrl() {
return TUMBLR_ACCESS_URL;
}
public static String getAuthorizeUrl() {
return TUMBLR_AUTHORIZE_URL;
}
public static OAuthConsumer getTumblrConsumer() {
return tumblrConsumer;
}
public static String getTumblrHost() {
return tumblrHost;
}
public static void setTumblrHost(String host) {
TumblrUtils.tumblrHost = host;
}
public static String getTumblrToken() {
return tumblrToken;
}
public static String getTumblrTokenSecret() {
return tumblrTokenSecret;
}
public static Intent getTumblrIntent(Context activity) {
Intent TumblrIntent = new Intent(activity, TumblrWebView.class);
TumblrIntent.putExtra("CONSUMER_KEY", getConsumerKey());
TumblrIntent.putExtra("CONSUMER_SECRET", getConsumerSecret());
TumblrIntent.putExtra("CALLBACK", getCallbackUrl());
return TumblrIntent;
}
public static OAuthConsumer saveTumblrResult(SharedPreferences settings,
String access_token, String secret_token) {
Editor editor = settings.edit();
editor.putString(PREF_TUMBLR_ACCESS, access_token);
editor.putString(PREF_TUMBLR_SECRET, secret_token);
editor.commit();
return saveTumblrResult(access_token, secret_token);
}
public static OAuthConsumer saveTumblrResult(String stringExtra1, String stringExtra2) {
tumblrToken = (stringExtra1);
tumblrTokenSecret = (stringExtra2);
tumblrConsumer = new CommonsHttpOAuthConsumer(
getConsumerKey(), getConsumerSecret());
tumblrConsumer.setTokenWithSecret(
tumblrToken, tumblrTokenSecret);
return tumblrConsumer;
}
}
EDIT: TumblrWebActivity - startActivityForResult
startActivityForResult(
TumblrUtils.getTumblrIntent(Settings_ShareSettings.this),
EDIT: TumblrWebActivity - onActivityResult
TumblrUtils.TUMBLR_REQUEST_CODE);
TumblrUtils.saveTumblrResult(mPrefs,
data.getStringExtra(TumblrUtils.PREF_TUMBLR_ACCESS),
data.getStringExtra(TumblrUtils.PREF_TUMBLR_SECRET));
new TumblrTask("https://api.tumblr.com/v2/user/info").execute();
EDIT: GetUserInfo - AsyncTask
private final class TumblrTask extends AsyncTask<String, Void, String> {
String url;
public TumblrTask(String url) {
this.url = url;
}
#Override
protected String doInBackground(String... params) {
String result = "";
HttpClient httpclient = GlobalContext.getHttpClient();
HttpRequestBase request = new HttpGet(url);
try {
TumblrUtils.getTumblrConsumer().sign(request);
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(request, GlobalContext.getLocalContext());
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();
result = GlobalContext.convertStreamToString(instream);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject jObject = new JSONObject(result.trim());
System.out.println(jObject);
if(jObject.has("response")) {
JSONObject jResponse = jObject.getJSONObject("response");
System.out.println(jResponse);
if(jResponse.has("user")) {
JSONObject jUser = jResponse.getJSONObject("user");
System.out.println(jUser);
tumblr_name = jUser.getString("name");
TumblrUtils.saveTumblrResult(mPrefs, tumblr_name);
tvTumblr.setText(tumblr_name);
ibTumblr.setSelected(true);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
EDIT: NOTE: Requires AndrOAuth
As it turns out, the Access Token and Access Token Secret returned were valid. The problem was that I was not signing the request with the Access Token Secret.

leaked a window ProgressDialog Android Dropbox

I am trying to upload a file to dropbox via AsyncTask and I am gett the window leaked error:
05-16 16:05:53.523: E/WindowManager(4528): Activity com.example.wecharades.ShowVideo has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#2be59ea8 that was originally added here
I looked here and understand it is because my activity is exited and the progressdialog is still there. I can't understand why my activity gets exited. it is just a screen with a button to press to upload the file. I am using almost an identical code to download a file from dropbox and it works perfect.
Any suggestions?
thanks in advance!
public class UploadFile extends AsyncTask<Void, Long, Boolean> {
DropboxAPI<AndroidAuthSession> dDBApi;
Context dContext;
protected final ProgressDialog uDialog;
private long dFileLen;
private String SAVE_PATH;
private String mErrorMsg;
public UploadFile(Context context,DropboxAPI<AndroidAuthSession> mDBApi, String path) {
dDBApi=mDBApi;
dContext=context;
SAVE_PATH = path;
uDialog = new ProgressDialog(context);
uDialog.setMax(100);
uDialog.setMessage("Uploading Video Charade");
uDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
uDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
FileInputStream inputStream = null;
try {
File file = new File(ShowVideo.path);
inputStream = new FileInputStream(file);
Entry newEntry = dDBApi.putFileOverwrite("/GAMES/GAME_BETWEEN_USER_A_USER_B/" + "PresentVideo.mp4", inputStream, file.length(), new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second
return 500;
}
#Override
public void onProgress(long bytes, long total) {
dFileLen = total;
publishProgress(bytes);
}
});
} catch (DropboxUnlinkedException e) {
// This session wasn't authenticated properly or user unlinked
mErrorMsg = "This app wasn't authenticated properly.";
} catch (DropboxFileSizeException e) {
// File size too big to upload via the API
mErrorMsg = "This file is too big to upload";
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Upload canceled";
} catch (DropboxServerException e) {
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._401_UNAUTHORIZED) {
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
} else if (e.error == DropboxServerException._403_FORBIDDEN) {
// Not allowed to access this
} else if (e.error == DropboxServerException._404_NOT_FOUND) {
// path not found (or if it was the thumbnail, can't be
// thumbnailed)
} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
// user is over quota
} else {
// Something else
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null) {
mErrorMsg = e.body.error;
}
} catch (DropboxIOException e) {
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
} catch (DropboxParseException e) {
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
} catch (DropboxException e) {
// Unknown error
mErrorMsg = "Unknown error. Try again.";
} catch (FileNotFoundException e) {
}
catch (Exception e) {
System.out.println("Something went wrong: " + e);
}
finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
Log.d("TAG", "IOException" + e.getMessage());
}
}
Log.d("ErrorMsg", mErrorMsg);
}
return null;
}
#Override
protected void onProgressUpdate(Long... progress) {
int percent = (int)(100.0*(double)progress[0]/dFileLen + 0.5);
uDialog.setProgress(percent);
}
#Override
protected void onPostExecute(Boolean result) {
uDialog.dismiss();
super.onPostExecute(result);
Log.d("TAG","UDialog Should be dismissed");
}
}
Here is my Activity class from where i call the UploadFile:
The methods buidSession and clearKeys are not yet used.
public class ShowVideo extends Activity implements OnClickListener {
/** Dropbox Key and AccessType Information*/
final static private String APP_KEY = "XXXXXXXXXXXX";
final static private String APP_SECRET = "XXXXXXXXXXXX";
final static private AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
/**--------------------------------------------------------------*/
private DropboxAPI<AndroidAuthSession> mDBApi;
UploadFile upload;
static String path = "";
public static String fileName;
private VideoView ww;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //Forces landscape orientation which is what the camera uses.
setContentView(R.layout.showvideo);
Button yesButton = (Button) findViewById(R.id.yesButton);
Button noButton = (Button) findViewById(R.id.NoButton);
yesButton.setOnClickListener(this);
noButton.setOnClickListener(this);
ww = (VideoView) findViewById(R.id.satisfiedVideoView);
path = getRealPathFromURI(CaptureVideo.uriVideo);
fileName = getFileNameFromUrl(path);
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
if(!mDBApi.getSession().isLinked())
mDBApi.getSession().startAuthentication(ShowVideo.this);
}
private void playVideo(){
ww.setVideoURI(CaptureVideo.uriVideo);
ww.setMediaController(new MediaController(this));
ww.start();
ww.requestFocus();
}
public static String getFileNameFromUrl(String path) {
String[] pathArray = path.split("/");
return pathArray[pathArray.length - 1];
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.yesButton){
UploadFile upload = new UploadFile(ShowVideo.this,mDBApi,path);
upload.execute();
//if(upload.getStatus() == upload.){
//Intent intentHome = new Intent(ShowVideo.this, StartScreen.class);
//startActivity(intentHome);
//}
}
if(v.getId() == R.id.NoButton){
File file = new File(path);
boolean deleted = false;
deleted = file.delete();
Log.d("TAG", Boolean.toString(deleted));
Intent intent = new Intent(ShowVideo.this, CaptureVideo.class);
startActivity(intent);
}
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**DROPBOX-METHOD------------------------------------------*/
#Override
protected void onResume() {
super.onResume();
AndroidAuthSession session = mDBApi.getSession();
// The next part must be inserted in the onResume() method of the
// activity from which session.startAuthentication() was called, so
// that Dropbox authentication completes properly.
if (session.authenticationSuccessful()) {
try {
// Mandatory call to complete the auth
session.finishAuthentication();
// Store it locally in our app for later use
TokenPair tokens = session.getAccessTokenPair();
storeKeys(tokens.key, tokens.secret);
//setLoggedIn(true);
} catch (IllegalStateException e) {
showToast("Couldn't authenticate with Dropbox:" + e.getLocalizedMessage());
Log.i("TAG", "Error authenticating", e);
}
}
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a local
* store, rather than storing user name & password, and re-authenticating each
* time (which is not to be done, ever).
*
* #return Array of [access_key, access_secret], or null if none stored
*/
private String[] getKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
String key = prefs.getString(ACCESS_KEY_NAME, null);
String secret = prefs.getString(ACCESS_SECRET_NAME, null);
if (key != null && secret != null) {
String[] ret = new String[2];
ret[0] = key;
ret[1] = secret;
return ret;
} else {
return null;
}
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a local
* store, rather than storing user name & password, and re-authenticating each
* time (which is not to be done, ever).
*/
private void storeKeys(String key, String secret) {
// Save the access key for later
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, key);
edit.putString(ACCESS_SECRET_NAME, secret);
edit.commit();
}
private void clearKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
private AndroidAuthSession buildSession() {
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session;
String[] stored = getKeys();
if (stored != null) {
AccessTokenPair accessToken = new AccessTokenPair(stored[0], stored[1]);
session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE, accessToken);
} else {
session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE);
}
return session;
}
private void showToast(String msg) {
Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
error.show();
}
}
Try this, in your constructor you dont get the context like this:
dContext=context.getApplicationContext();
but try passing the activity from which you start your asynctask
UploadFile upFile = new UploadFile( ActivityName.this, mDBApi, path);
so in your constructor you have now only:
dContext=context;
call super.onPostExexute(result) after uDialog.dismiss();
#Override
protected void onPostExecute(Boolean result) {
uDialog.dismiss();
Log.d("TAG","UDialog Should be dismissed");
super.onPostExecute(result);
}
EDIT:
ok, I think you should call this code
if(v.getId() == R.id.NoButton){
File file = new File(path);
boolean deleted = false;
deleted = file.delete();
Log.d("TAG", Boolean.toString(deleted));
Intent intent = new Intent(ShowVideo.this, CaptureVideo.class);
startActivity(intent);
}
in the onPostExecute trigger, because it's executed without waiting the AsyncTask to finish. This means you will have to pass the value of the v.getId() so you can achive the same functionality.

Twitter not getting the access token and access token secret Android

I'm implementing twitter tweet message in my Android app. I'm able to implement Twitter log in but I guess I'm not able to save the access token after logging in, because when I tweet a message it doesn't appear to my twitter wall. I also try to toast the access token and access toke secret but it is both blank.
Here is my codes:
public class MainActivity extends Activity {
Intent intent;
static String TWITTER_CONSUMER_KEY = "hide key";
static String TWITTER_CONSUMER_SECRET = "hide key";
// 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();
#SuppressLint("NewApi")
#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);
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);
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Call login twitter function
loginToTwitter();
}
});
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());
}
}
}
btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
sendToTwitter(status);
}
});
}
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
twitter4j.conf.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();
}
}
/**
* 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);
}
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
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() {
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
txtUpdate.setText("");
}
});
}
}
public static void sendToTwitter(String tweet) {
String access_token1 = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
String access_token_secret1 = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("8yTg3E1eHq6YF6l6stS4tQ")
.setOAuthConsumerSecret("6spBb7gxsuUMfv50CWSjMZLVhHUEoLXxg97txoon45w")
.setOAuthAccessToken(access_token1)
.setOAuthAccessTokenSecret(access_token_secret1);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter t = tf.getInstance();
try {
t.updateStatus(tweet);
} catch (TwitterException te) {
te.printStackTrace();
}
}
Can anyone point what is wrong or missing on my codes? It doesn't throw any error btw.
Try like this ...
private TwitterSession mSession;
private AccessToken mAccessToken;
private CommonsHttpOAuthConsumer mHttpOauthConsumer;
private OAuthProvider mHttpOauthprovider;
private String mConsumerKey;
private String mSecretKey;
private ProgressDialog mProgressDlg;
private TwDialogListener mListener;
private Activity context;
public static final String CALLBACK_URL = "twitterapp://connect";
private static final String TWITTER_ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token";
private static final String TWITTER_AUTHORZE_URL = "https://api.twitter.com/oauth/authorize";
private static final String TWITTER_REQUEST_URL = "https://api.twitter.com/oauth/request_token";
public static final String MESSAGE = "There is lot more to come, Subscribe to http://....";
public TwitterApp(Activity context, String consumerKey, String secretKey) {
Log.d("tag", consumerKey + ";" + secretKey);
this.context = context;
mTwitter = new TwitterFactory().getInstance();
mSession = new TwitterSession(context);
mProgressDlg = new ProgressDialog(context);
mConsumerKey = consumerKey;
mSecretKey = secretKey;
mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey,
mSecretKey);
String request_url = TWITTER_REQUEST_URL;
String access_token_url = TWITTER_ACCESS_TOKEN_URL;
String authorize_url = TWITTER_AUTHORZE_URL;
mHttpOauthprovider = new DefaultOAuthProvider(request_url,
access_token_url, authorize_url);
mAccessToken = mSession.getAccessToken();
Log.d("tag", "Access_Token: " + mAccessToken);
configureToken();
}
public void setListener(TwDialogListener listener) {
mListener = listener;
}
#SuppressWarnings("deprecation")
private void configureToken() {
if (mAccessToken != null) {
mTwitter.setOAuthConsumer(mConsumerKey, mSecretKey);
mTwitter.setOAuthAccessToken(mAccessToken);
}
}
public boolean hasAccessToken() {
return (mAccessToken == null) ? false : true;
}
public void resetAccessToken() {
if (mAccessToken != null) {
mSession.resetAccessToken();
mAccessToken = null;
}
}
public String getUsername() {
return mSession.getUsername();
}
public void updateStatus(String status) throws Exception {
try {
mTwitter.updateStatus(status);
} catch (TwitterException e) {
Log.d("Twitter Exception * Update Status * tag", e.getMessage());
throw e;
}
}
public void authorize() {
mProgressDlg.setMessage("Initializing...");
mProgressDlg.show();
new Thread() {
#Override
public void run() {
String authUrl = "";
int what = 1;
try {
authUrl = mHttpOauthprovider.retrieveRequestToken(
mHttpOauthConsumer, CALLBACK_URL);
what = 0;
} catch (Exception e) {
Log.d("Twitter Exception * Authorize * tag", e.getMessage());
}
mHandler.sendMessage(mHandler
.obtainMessage(what, 1, 0, authUrl));
}
}.start();
}
public void processToken(String callbackUrl) {
mProgressDlg.setMessage("Finalizing...");
mProgressDlg.show();
final String verifier = getVerifier(callbackUrl);
new Thread() {
#Override
public void run() {
int what = 1;
try {
mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer,
verifier);
mAccessToken = new AccessToken(
mHttpOauthConsumer.getToken(),
mHttpOauthConsumer.getTokenSecret());
configureToken();
User user = mTwitter.verifyCredentials();
mSession.storeAccessToken(mAccessToken, user.getName());
what = 0;
} catch (Exception e) {
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}
private String getVerifier(String callbackUrl) {
String verifier = "";
try {
callbackUrl = callbackUrl.replace("twitterapp", "http");
URL url = new URL(callbackUrl);
String query = url.getQuery();
String array[] = query.split("&");
for (String parameter : array) {
String v[] = parameter.split("=");
if (URLDecoder.decode(v[0]).equals(
oauth.signpost.OAuth.OAUTH_VERIFIER)) {
verifier = URLDecoder.decode(v[1]);
break;
}
}
} catch (MalformedURLException e) {
}
return verifier;
}
private void showLoginDialog(String url) {
final TwDialogListener listener = new TwDialogListener() {
public void onComplete(String value) {
processToken(value);
}
public void onError(String value) {
mListener.onError("Failed opening authorization page");
}
};
new TwitterDialog(context, url, listener).show();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mProgressDlg.dismiss();
if (msg.what == 1) {
if (msg.arg1 == 1)
mListener.onError("Error getting request token");
else
mListener.onError("Error getting access token");
} else {
if (msg.arg1 == 1)
showLoginDialog((String) msg.obj);
else
mListener.onComplete("");
}
}
};
public interface TwDialogListener {
public void onComplete(String value);
public void onError(String value);
}
}
public class TwitterSession {
private SharedPreferences sharedPref;
private static Editor editor;
private static final String TWEET_AUTH_KEY = "auth_key";
private static final String TWEET_AUTH_SECRET_KEY = "auth_secret_key";
private static final String TWEET_USER_NAME = "user_name";
private static final String SHARED = "Twitter_Preferences";
public TwitterSession(Context context) {
sharedPref = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);
editor = sharedPref.edit();
}
public void storeAccessToken(AccessToken accessToken, String username) {
editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
editor.putString(TWEET_AUTH_SECRET_KEY, accessToken.getTokenSecret());
editor.putString(TWEET_USER_NAME, username);
editor.commit();
}
public void resetAccessToken() {
editor.putString(TWEET_AUTH_KEY, null);
editor.putString(TWEET_AUTH_SECRET_KEY, null);
editor.putString(TWEET_USER_NAME, null);
editor.commit();
}
public String getUsername() {
return sharedPref.getString(TWEET_USER_NAME, "");
}
public AccessToken getAccessToken() {
String token = sharedPref.getString(TWEET_AUTH_KEY, null);
String tokenSecret = sharedPref.getString(TWEET_AUTH_SECRET_KEY, null);
if (token != null && tokenSecret != null)
return new AccessToken(token, tokenSecret);
else
return null;
}
}

Android: Can't post tweet using OAuth and twitter

I am trying to send tweets to twitter via my android app. The libraries I'm using are signpost core, signpost commonshttp, and jtwitter. My code in my main activity is as follows:
public class MainActivity extends Activity implements View.OnClickListener {
static final String TAG = "TweetExample";
private Twitter twitter;
SharedPreferences prefs;
private EditText textStatus;
private static final String CONSUMER_KEY = "my key";
private static final String CONSUMER_SECRET = "my secret";
private static String ACCESS_KEY = null;
private static String ACCESS_SECRET = null;
private static final String REQUEST_URL = "http://twitter.com/oauth/request_token";
private static final String ACCESS_TOKEN_URL = "http://twitter.com/oauth/access_token";
private static final String AUTH_URL = "http://twitter.com/oauth/authorize";
private static final String CALLBACK_URL = "TweetExample://twitt";
private static CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
private static CommonsHttpOAuthProvider provider = new CommonsHttpOAuthProvider
(REQUEST_URL, ACCESS_TOKEN_URL, AUTH_URL);
//Called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Retrieve the shared preferences
prefs = getSharedPreferences(USER_PREFERENCES,
Context.MODE_PRIVATE);
// Find views by id
ImageView buttonUpdate = (ImageView) findViewById(R.id.ImageView_Update);
textStatus = (EditText) findViewById(R.id.textStatus);
ImageView btnLogin = (ImageView) findViewById(R.id.ImageView_Twit);
// Add listener
buttonUpdate.setOnClickListener(this);
btnLogin.setOnClickListener(this);
// Initialize preferences
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) {
twitter = null;
}
});
}
public void onClick(View v) {
switch(v.getId()){
case R.id.ImageView_Update:
String status = textStatus.getText().toString();
String message = "Status set to: " + status;
Log.d(TAG, message);
// Ignore empty updates
if (status.length() == 0)
return;
// Connect to twitter.com and update your status
try {
Log.d(TAG, "1");
twitter.setStatus(status);
Log.d(TAG, "2");
} catch (TwitterException e) {
Log.e(TAG, "Twitter exception: " + e);
}
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
break;
case R.id.ImageView_Twit:
try {
String authURL = provider.retrieveRequestToken(consumer, CALLBACK_URL);
Log.d(TAG, authURL);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authURL)));
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
break;
}
}
#Override
public void onResume() {
super.onResume();
Uri uri = this.getIntent().getData();
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
Log.d(TAG, uri.toString());
String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
Log.d(TAG, verifier);
try {
provider.retrieveAccessToken(consumer, verifier);
ACCESS_KEY = consumer.getToken();
ACCESS_SECRET = consumer.getTokenSecret();
Log.d(TAG, ACCESS_KEY);
Log.d(TAG, ACCESS_SECRET);
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
}
}
I know the callback url is right. Could it be that I authenticate using signpost and try to tweet using jtwitter? Right now, I can sign into twitter to authorize the app and get redirected back to my app, but when I type something in to try to post to twitter it gets as far as twitter.setStatus(status);
Any help would be greatly appreciated.
Possibly I'm being blind, or you forgot to include some code, but it looks like the Twitter object is never constructed. So you'd get a NullPointerException when you come to use it.
Somewhere you want code along the lines of:
OAuthSignpostClient oauthClient = new OAuthSignpostClient(app_token, app_secret, user_access_token, user_secret);
Twitter twitter = new Twitter(null, oauthClient);

Twitter OAuth with Android - Still getting a 401 but no glue where the mistake is located

I'm experiencing some problems regarding Twitter OAuth within an android activity. I read a lot of tutorials and example code, but I'm still not able to receive the access token.
Everytime I try to authorize I'm getting this OAuthNotAuthorizedException:
oauth.signpost.exception.OAuthNotAuthorizedException: Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match.
I googled a lot and it felt like I read thousands of solutions, but none of them worked out for me. Hope you can help me with this one (and I'm not bothering your with the same old newbie question! ;) )
Here is my complete activity code:
package de.ownor.moremote;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class MakeTweet extends Activity {
public static final String CONSUMER_KEY = "Y0iYMkUgNX8kKgvDjzFgg";
public static final String CONSUMER_SECRET = "nuBZd8UGml5cjbm94Hf6dWOwIByrisZWpSnqODaUB5Q";
public static final String CALLBACK_URL = "de.ownor.moremote://twitter";
private static final String REQUEST_URL = "https://api.twitter.com/oauth/request_token";
private static final String ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token";
private static final String AUTH_URL = "https://api.twitter.com/oauth/authorize";
public static final String PREFS_NAME = "TwitterLogin";
public static final String TAG = "moremote - MakeTweet";
private Twitter twitter;
private CommonsHttpOAuthProvider provider;
private CommonsHttpOAuthConsumer consumer;
#Override
protected void onCreate(Bundle savedInstanceState) {
System.setProperty("http.keepAlive", "false");
super.onCreate(savedInstanceState);
setContentView(R.layout.make_tweet);
twitter = null;
if (!checkForSavedLogin()) {
askOAuth();
}
getConsumerProvider();
}
#Override
protected void onResume() {
super.onResume();
System.out.println("RESUMING!!");
if (this.getIntent() != null && this.getIntent().getData() != null) {
Uri uri = this.getIntent().getData();
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
String verifier = uri
.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
try {
// this will populate token and token_secret in consumer
// /////////////////////////////
// exception is thrown here! //
// /////////////////////////////
provider.retrieveAccessToken(consumer, verifier);
// Get Access Token and persist it
AccessToken a = new AccessToken(consumer.getToken(),
consumer.getTokenSecret());
storeAccessToken(a);
// initialize Twitter4J
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
((ApplicationEx) getApplication()).twitter = twitter;
} catch (Exception e) {
// Log.e(APP, e.getMessage());
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG)
.show();
}
}
}
}
private void askOAuth() {
try {
consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY,
CONSUMER_SECRET);
provider = new CommonsHttpOAuthProvider(REQUEST_URL,
ACCESS_TOKEN_URL, AUTH_URL);
provider.setOAuth10a(true);
String authUrl = provider.retrieveRequestToken(consumer,
CALLBACK_URL);
Toast.makeText(this, "Please authorize this app!",
Toast.LENGTH_LONG).show();
setConsumerProvider();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (Exception e) {
Log.e(TAG, "Error in askOAuth");
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private Boolean checkForSavedLogin() {
// Get Access Token and persist it
AccessToken a = getAccessToken();
if (a == null) {
Log.d(TAG, "No saved Login found");
return false;
}
// initialize Twitter4J
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
((ApplicationEx) getApplication()).twitter = twitter;
return true;
}
private AccessToken getAccessToken() {
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
MODE_PRIVATE);
String token = settings.getString("accessTokenToken", "");
String tokenSecret = settings.getString("accessTokenSecret", "");
if (token != null && tokenSecret != null && !"".equals(tokenSecret)
&& !"".equals(token)) {
return new AccessToken(token, tokenSecret);
}
return null;
}
private void storeAccessToken(AccessToken a) {
SharedPreferences settings = Preferences.getPreferences(this);
SharedPreferences.Editor editor = settings.edit();
editor.putString("accessTokenToken", a.getToken());
editor.putString("accessTokenSecret", a.getTokenSecret());
editor.commit();
}
private void getConsumerProvider() {
CommonsHttpOAuthProvider p = ((ApplicationEx) getApplication()).provider;
if (p != null) {
provider = p;
}
CommonsHttpOAuthConsumer c = ((ApplicationEx) getApplication()).consumer;
if (c != null) {
consumer = c;
}
}
private void setConsumerProvider() {
if (provider != null) {
((ApplicationEx) getApplication()).provider = provider;
}
if (consumer != null) {
((ApplicationEx) getApplication()).consumer = consumer;
}
}
}
The exception is thrown in the onResume()-Method. I marked the exact line. I really hope anyone can help me here. If you need further information just scream!
Thanks!
Simon.
I finally managed to get the OAuth running. Unless I don't know the exact error. I guess it was some issue with the consumer.
Here is my running code:
onCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.twitter);
pref = Preferences.getPreferences(this);
consumer = new CommonsHttpOAuthConsumer(Key.TW_CONSUMER_KEY,
Key.TW_CONSUMER_SECRET);
provider = new CommonsHttpOAuthProvider(Key.TW_REQUEST_TOKEN_URL,
Key.TW_ACCESS_TOKEN_URL, Key.TW_AUTHORIZE_URL);
provider.setOAuth10a(true);
[...]
if (getIntent().getData() == null) {
checkForSavedLogin();
}
}
onResume:
protected void onResume() {
super.onResume();
Uri uri = getIntent().getData();
if (uri != null
&& Key.TW_CALLBACK_URI.getScheme().equals(uri.getScheme())) {
String token = pref.getString(Key.TW_REQUEST_TOKEN, null);
String secret = pref.getString(Key.TW_REQUEST_SECRET, null);
try {
if (!(token == null || secret == null)) {
consumer.setTokenWithSecret(token, secret);
}
String otoken = uri.getQueryParameter(OAuth.OAUTH_TOKEN);
String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
Assert.assertEquals(otoken, consumer.getToken());
provider.retrieveAccessToken(consumer, verifier);
token = consumer.getToken();
secret = consumer.getTokenSecret();
saveAuthInformation(token, secret);
// Delete request information
saveRequestInformation(null, null);
if (!(token == null || secret == null)) {
Log.d(TAG, "Twitter login found!");
consumer.setTokenWithSecret(token, secret);
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Key.TW_CONSUMER_KEY,
Key.TW_CONSUMER_SECRET);
twitter.setOAuthAccessToken(new AccessToken(token, secret));
}
} catch (Exception e) {
Log.d(TAG, "Couldn't receive token" + e.getMessage());
e.printStackTrace();
}
}
[...]
}
other methods:
private void checkForSavedLogin() {
if (pref.contains(Key.TW_USER_TOKEN)
&& pref.contains(Key.TW_USER_SECRET)) {
token = pref.getString(Key.TW_USER_TOKEN, null);
secret = pref.getString(Key.TW_USER_SECRET, null);
if (!(token == null || secret == null)) {
Log.d(TAG, "Twitter login found!");
consumer.setTokenWithSecret(token, secret);
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Key.TW_CONSUMER_KEY,
Key.TW_CONSUMER_SECRET);
twitter.setOAuthAccessToken(new AccessToken(token, secret));
}
} else {
Log.d(TAG, "No Twitter login saved - asking for OAuth");
askOAuth();
}
}
private void askOAuth() {
try {
String authUrl = provider.retrieveRequestToken(consumer,
Key.TW_CALLBACK_URI.toString());
saveRequestInformation(consumer.getToken(),
consumer.getTokenSecret());
Toast.makeText(this, "Please authorize this app!",
Toast.LENGTH_LONG).show();
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(authUrl)));
} catch (OAuthException e) {
e.printStackTrace();
}
}
private void saveRequestInformation(String token, String secret) {
// null means to clear the old values
SharedPreferences.Editor editor = pref.edit();
if (token == null) {
editor.remove(Key.TW_REQUEST_TOKEN);
} else {
editor.putString(Key.TW_REQUEST_TOKEN, token);
}
if (secret == null) {
editor.remove(Key.TW_REQUEST_SECRET);
} else {
editor.putString(Key.TW_REQUEST_SECRET, secret);
}
editor.commit();
}
private void saveAuthInformation(String token, String secret) {
pref = Preferences.getPreferences(this);
Editor editor = pref.edit();
editor.putString(Key.TW_USER_TOKEN, token);
editor.putString(Key.TW_USER_SECRET, secret);
editor.commit();
}
Feel free to use this code... :)
¿Are you using
mHttpOauthprovider = new DefaultOAuthProvider("https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
"https://api.twitter.com/oauth/authorize");
with HTTPS protocol?

Categories

Resources