AsyncTask - onPostExecute is never called - android

I'm using an asyncTask in my app, but it's not calling the onPostExecute method. I read it dozen of times and couldn't find an error.
It flows like this:
MainActivity
--> user clicks on button
-->calls a class
-->call another class with a method that show some messages and then executes the AsyncTask.
This is the full class and the AsyncTask:
package com.vdlow.socialnotification.twitter;
import java.util.ArrayList;
import com.vdlow.socialnotification.R;
import oauth.signpost.OAuth;
import twitter4j.IDs;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
public class TwitterUtils {
static long userID;
static Context c;
static Boolean retornoSend;
public static boolean isAuthenticated(SharedPreferences prefs) {
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_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, Context cs) throws Exception {
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
String values[] = {token, secret, msg};
TwitterUtils tu = new TwitterUtils();
TweetSender ts = tu.new TweetSender();
ts.execute(values);
Log.i("retornoSend", retornoSend.toString());
if(retornoSend){
Toast.makeText(cs, cs.getString(R.string.tweet_sent), Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(cs, cs.getString(R.string.fail_sending), Toast.LENGTH_LONG).show();
}
}
public static ArrayList<String> getUserId(final SharedPreferences prefs) throws Exception{
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_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 {
userID = twitter.getId();
} catch (IllegalStateException e) {
Log.e("Error! Method: getUserId() Class: TwitterUtils", e.toString());
}
Log.i("USERID", String.valueOf(userID));
ArrayList<String> following = new ArrayList<String>();
long lCursor = -1;
try{
userID = twitter.getId();
IDs friendsIDs = twitter.getFriendsIDs(userID, lCursor);
do
{
for (long i : friendsIDs.getIDs())
{
following.add("#"+twitter.showUser(i).getScreenName());
}
}while(friendsIDs.hasNext());
}
catch(Exception e){
Log.e("Exception! Class TwitterUtils Method: getFriendsName()", e.toString()+"\n User ID "+String.valueOf(userID));
}
return following;
}
private class TweetSender extends AsyncTask<String, Void, Boolean>{
#Override
protected Boolean doInBackground(String... msg) {
Looper.prepare();
String token = msg[0];
String secret = msg[1];
AccessToken a = new AccessToken(token,secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
try {
twitter.updateStatus(msg[2]);
} catch (TwitterException e) {
Log.e("Error sending tweet Class TwitterUtils Method sendTweet() AsyncTask TweetSender", e.toString());
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result){
Log.i("Post execute", "Runned");
retornoSend = result;
}
}
Any ideas why it's not working?

Your doInBackground is either never completing, or you cancel the request at some point:
from the developer docs (see bold text below): http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean)
Attempts to cancel execution of this task. This attempt will fail if
the task has already completed, already been cancelled, or could not
be cancelled for some other reason. If successful, and this task has
not started when cancel is called, this task should never run. If the
task has already started, then the mayInterruptIfRunning parameter
determines whether the thread executing this task should be
interrupted in an attempt to stop the task.
Calling this method will result in onCancelled(Object) being invoked
on the UI thread after doInBackground(Object[]) returns. Calling
this method guarantees that onPostExecute(Object) is never invoked.
After invoking this method, you should check the value returned by
isCancelled() periodically from doInBackground(Object[]) to finish the
task as early as possible.

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

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

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

Android Async Task Error with ClientService

I am creating simple system that has a windows service running, complete with a table of users, and I want to validate someone's login credentials by sending something to the service. I am trying to send their username and password, but I keep getting an error with my Async Task. I know that you're not supposed to mess with UI stuff in there and I am not. Originally I had a call to another activity in there but I commented it out. Now the only thing in doInBackground is setting a boolean value to true if the validation was good. From there I read the value after the async has executed, and then put together a bundle to move to the next place. I just don't know what's wrong here. It has been awhile since I've programmed in Android so maybe I'm missing something stupid. If anyone could help me out I would greatly appreciate it! Thank you. This could also be an issue with sending the information to the service?
UPDATE: After adding in the internet usage in the manifest, if I have the log.d in the program in my doInBackground, it prints out. If I don't have it, the result value stays false. It looks like there is some issue with the connection between my service and android app...
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
private static final int DATA_FROM_MAIN_ACTIVITY = 1;
private static final String SERVICEURL = "http://localhost:56638/ClientService.svc";
private EditText userTextBox, passTextBox;
private Button loginButton;
private String uName, pass;
private Boolean result = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userTextBox = (EditText) findViewById(R.id.userTextBox);
passTextBox = (EditText) findViewById(R.id.passTextBox);
loginButton = (Button) findViewById(R.id.loginButton);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uName = userTextBox.getText().toString();
pass = passTextBox.getText().toString();
SendLoginMessage task = new SendLoginMessage();
task.execute(uName, pass);
if (result.equals(true)) {
Intent goToMainScreen = new Intent(getApplicationContext(),
MainActivity.class);
goToMainScreen.putExtra("username", uName);
goToMainScreen.putExtra("password", pass);
startActivityForResult(goToMainScreen,
DATA_FROM_MAIN_ACTIVITY);
} else {
Toast.makeText(
getApplicationContext(),
"There was an issue with your username or password.",
Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class SendLoginMessage extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// Log.d("message almost at server, " + textFromArea, selected,
// null);
}
#Override
protected Void doInBackground(String... names) {
ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("username", names[0]));
postParams.add(new BasicNameValuePair("password", names[1]));
String response = null;
try {
response = HttpClient.executeHttpPost(SERVICEURL, postParams);
String newResponse = response.toString();
newResponse = newResponse.replaceAll("\\s+", "");
// if user was authenticated...
if (newResponse.equals(true)) {
result = true;
// creating an intent to take user to next page.
// load their DB objects on the
// on create in other activity
// pass the username/password to next activity
// then make a request to the server for their database
// objects.
// Intent goToMainScreen = new
// Intent(getApplicationContext(), MainActivity.class);
// goToMainScreen.putExtra("username", names[0]);
// goToMainScreen.putExtra("password", names[1]);
// startActivityForResult(goToMainScreen,
// DATA_FROM_MAIN_ACTIVITY);
}
} catch (Exception e) {
Log.d("ERROR", "exception in background");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Toast.makeText(getApplicationContext(),
// .show();
}
}
}
Do it like this:
private class SendLoginMessage extends AsyncTask<String, String, Boolean> {
#Override
protected Boolean doInBackground(String... names) {
ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("username", names[0]));
postParams.add(new BasicNameValuePair("password", names[1]));
String response = null;
try {
response = HttpClient.executeHttpPost(SERVICEURL, postParams);
String newResponse = response.toString();
newResponse = newResponse.replaceAll("\\s+", "");
// if user was authenticated...
if (newResponse.equals("true")) {
return true;
}
} catch (Exception e) {
Log.d("ERROR", "exception in background");
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
Intent goToMainScreen = new Intent(getApplicationContext(),
MainActivity.class);
goToMainScreen.putExtra("username", uName);
goToMainScreen.putExtra("password", pass);
startActivityForResult(goToMainScreen,
DATA_FROM_MAIN_ACTIVITY);
} else {
Toast.makeText(
getApplicationContext(),
"There was an issue with your username or password.",
Toast.LENGTH_LONG).show();
}
}
}
and in your onClick() just call execute()
uName = userTextBox.getText().toString();
pass = passTextBox.getText().toString();
SendLoginMessage task = new SendLoginMessage();
task.execute(uName, pass);
After execution is finished onPostExecute() will be called and your Activity will start depending on result variable.
Don't check your result variable after you invoke execute() because execute() is invoked asynchronously. By the time you check your global result variable, your doInBackground() might not have been finished. Using my approach you don't need a global variable. Please read doc carefully before using any component.

want to interrupt a thread but thread is null

I want to interrupt a thread1 from another thread2 but when I try make the thread1.interrupt(); call I get a null pointer error.
I'm making an android app, I'm on an android login page and when I login I create and start a thread called sessionTimer (which does a session countdown say 2min). What I want is that when I press logout in a different activity that I go to the login page and my sessionTimer thread should be interrupted so that I can start a new login session with max time.
package com.AndroidApp.Login;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.AndroidApp.R;
import com.AndroidApp.domain.Utente;
import com.AndroidApp.pagine.MenuPagina;
public class LoginActivity extends Activity {
final String TAG = "LogIN";
ArrayList<HashMap<String, String>> mylist;
private Button bLogin, bExit;
private EditText utente, passwd;
private MediaPlayer mpButtonClick = null;
private SharedPreferences mPreferences;
public volatile Thread sessionTimer;
public long tId = -1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
SharedPreferences.Editor editor = mPreferences.edit();
editor.clear();
editor.commit();
String nome = mPreferences.getString("nome", "Nessuno");
setTitle("Sessione di : " + nome);
Log.w("TotThreads", Integer.toString(Thread.activeCount()));
/*
final SessionTimer st = new SessionTimer();
*/
if(MenuPagina.reset){
Log.w("sessionTimer ID", Long.toString(sessionTimer.getId()));
if (sessionTimer == null)
Log.w("sessionTimer", "sessionTimer is NULL");
sessionTimer.interrupt();
System.out.println("end current session");
//st.stopRequest();
}
if (!checkLoginInfo()) {
mpButtonClick = MediaPlayer.create(this, R.raw.button);
bLogin = (Button)findViewById(R.id.bLogin);
bLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mpButtonClick.start();
Log.v(TAG, "Trying to Login");
utente = (EditText)findViewById(R.id.etUtente);
passwd = (EditText)findViewById(R.id.etPassword);
String username = utente.getText().toString();
username = ("ccce#eex.it");
String password = md5(passwd.getText().toString());
password = md5("12345");
XMLFunctionsLogin.getInstance().setNewURL("u=" + username + "&p=" + password);
String xml = XMLFunctionsLogin.getXML();
Document doc = XMLFunctionsLogin.xmlFromString(xml);
int status = XMLFunctionsLogin.errStatus(doc);
Log.v("status", Integer.toString(status));
if ((status == 0)) {
NodeList nodes = doc.getElementsByTagName("login");
Element e = (Element) nodes.item(0);
Utente utente = new Utente();
utente.setIdUtente(XMLFunctionsLogin.getValue(e, "idUtente"));
utente.setNome(XMLFunctionsLogin.getValue(e, "nome"));
utente.setCognome(XMLFunctionsLogin.getValue(e, "cognome"));
Log.v("utente", utente.getCognome().toString());
List<NameValuePair> nvps = new ArrayList<NameValuePair>(2);
nvps.add(new BasicNameValuePair("utente", username));
nvps.add(new BasicNameValuePair("password", password));
Log.v(TAG, nvps.get(0).toString());
Log.v(TAG, nvps.get(1).toString());
// Store the username and password in SharedPreferences after the successful login
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString("userName", username);
editor.putString("password", password);
editor.putString("idUtente", utente.getIdUtente());
editor.putString("nome", utente.getNome());
editor.putString("cognome", utente.getCognome());
editor.commit();
Log.v(TAG, "timer");
Log.v("RESET", Boolean.toString(MenuPagina.reset));
/*
Thread t = new Thread(st);
t.start();
*/
sessionTimer = new Thread() {
#Override
public void run() {
long tId = Thread.currentThread().getId();
Log.w("TTthread Id", Long.toString(tId));
for (int i = 30; i >= 0; i -= 1) {
if ((i == 0) || (MenuPagina.reset)) {
System.out.print("timer finito");
Log.i("Timer", "timer finito");
LoginActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(LoginActivity.this, "ti si รจ scaduta la sessione", Toast.LENGTH_LONG).show();
}
});
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
//System.exit(0);
} try {
Thread.sleep(1000);
Log.i("Timer", Integer.toString(i));
} catch (InterruptedException e) {
Log.i("Catch", "Catchhhhhhhhhhhh");
e.printStackTrace();
Thread.currentThread().interrupt();
return;
}
}
}
};
sessionTimer.start();
Log.v(TAG, "Successo2");
Toast.makeText(LoginActivity.this, "LogIn con successo", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext()/*LoginActivity.this*/, MenuPagina.class);
startActivity(intent);
} else {
final String errorMessage = XMLFunctionsLogin.errStatusDesc(doc);
Log.v("fallimento", errorMessage);
LoginActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_LONG).show();
}
});
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
});
bExit = (Button)findViewById(R.id.bExit);
bExit.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mpButtonClick.start();
finish();
}
});
}
}
//Checking whether the username and password has stored already or not
private final boolean checkLoginInfo() {
boolean username_set = mPreferences.contains("UserName");
boolean password_set = mPreferences.contains("PassWord");
if ( username_set || password_set ) {
return true;
}
return false;
}
//md5 for crypting and hash
private static String md5(String data) {
byte[] bdata = new byte[data.length()];
int i;
byte[] hash;
for (i = 0; i < data.length(); i++)
bdata[i] = (byte) (data.charAt(i) & 0xff);
try {
MessageDigest md5er = MessageDigest.getInstance("MD5");
hash = md5er.digest(bdata);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
StringBuffer r = new StringBuffer(32);
for (i = 0; i < hash.length; i++) {
String x = Integer.toHexString(hash[i] & 0xff);
if (x.length() < 2)
r.append("0");
r.append(x);
}
return r.toString();
}
}
So what happens is when I logout and I come back to the login page and MenuPagina.reset = true I get an error saying that sessionTimer is null. Why?
I've tried also using a seperate class for the thread but I get the same null pointer error.
onCreate runs when your Activity is being created or re-created, either way it's a new object, so any local variables have to be initialized again, in your case sessionTimer would be null until the new Thread() {} call.
If you need to persist a reference to your thread, use more global object than your Activity is - Application, that's a base class for maintaining global application state. You can always access it by calling Context.getApplicationContext(). Anyway, read the docs.

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>

Categories

Resources