尝试使用twitter4j-4.0.1跟踪用户时收到身份验证null

时间:2014-04-07 06:43:39

标签: android twitter-oauth twitter4j

我正在尝试创建一个应用程序,要求我有关注按钮,以便用户可以在Twitter上关注我的屏幕名称。

我可以让用户登录到他们的用户帐户并发布但是当我尝试制作然后按照我的屏幕名称时,Logcat会显示我"收到的身份验证质询为空"但是我在尝试登录时使用了相同的Twitter对象。

我正在粘贴下面的代码

 static String TWITTER_CONSUMER_KEY = "LsCQaPOwd8k7WkyRFRZF4Q";
static String TWITTER_CONSUMER_SECRET = "KJbJu5IQrlwxW7Cwnax3mMzAc4j3n6Wd2dG125srgk";

// 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";

Button btnLoginTwitter;
// Update status button
Button btnUpdateStatus;
// Logout button
Button btnLogoutTwitter;
// EditText for update
EditText txtUpdate;
// lbl update
TextView lblUpdate;
TextView lblUserName;
Button follow;
// Progress dialog
ProgressDialog pDialog;

// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
private AccessToken accessToken;
private User user;

// Shared Preferences
private static SharedPreferences mSharedPreferences;

// Internet Connection detector
private ConnectionDetector cd;

// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    cd = new ConnectionDetector(getApplicationContext());

    // Check if Internet present
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(MainActivity.this, "Internet Connection Error", "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }

    // Check if twitter keys are set
    if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
        // Internet Connection is not present
        alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
        // stop executing code by return
        return;
    }

    // All UI elements
    btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
    btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
    btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
    follow = (Button) findViewById(R.id.followTwitter);
    txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
    lblUpdate = (TextView) findViewById(R.id.lblUpdate);
    lblUserName = (TextView) findViewById(R.id.lblUserName);

    // Shared Preferences
    mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);

    /**
     * Twitter login button click event will call loginToTwitter() function
     * */
    btnLoginTwitter.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Call login twitter function
            loginToTwitter();
        }
    });

    follow.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
           new FollowFriend().execute();

        }
    });

    /**
     * Button click event to Update Status, will call updateTwitterStatus()
     * function
     * */
    btnUpdateStatus.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Call update status function
            // Get the status from EditText
            String status = txtUpdate.getText().toString();

            // Check for blank text
            if (status.trim().length() > 0) {
                // update status
                new updateTwitterStatus().execute(status);
            } else {
                // EditText is empty
                Toast.makeText(
                        getApplicationContext(),
                        "Please enter status message", 
                        Toast.LENGTH_SHORT
                ).show();
            }
        }
    });

    /**
     * Button click event for logout from twitter
     * */
    btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Call logout twitter function
            logoutFromTwitter();
        }
    });

    /** This if conditions is tested once is
     * redirected from twitter page. Parse the uri to get oAuth
     * Verifier
     * */
    if (!isTwitterLoggedInAlready()) {
        Uri uri = getIntent().getData();
        if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {

            // oAuth verifier
            String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
            new OAuthAccessTokenTask().execute(verifier);
        }
    }

}
 class FollowFriend extends AsyncTask<Void, Void, Void>
 {

    @Override
    protected Void doInBackground(Void... arg0) {
         try {

                twitter.createFriendship("xyz");
             System.out.println("Successfully followed ");
         } catch (TwitterException te) {
             te.printStackTrace();
             System.out.println("Failed to follow: " + te.getMessage());


         }
        return null;
    }

 }
 private class OAuthAccessTokenTask extends AsyncTask<String, Void, Exception>
 {
    @Override
    protected Exception doInBackground(String... params) {
        Exception toReturn = null;

        try {
            accessToken = twitter.getOAuthAccessToken(requestToken, params[0]);
            user = twitter.showUser(accessToken.getUserId());

        }
        catch(TwitterException e) {
            Log.e(MainActivity.class.getName(), "TwitterError: " + e.getErrorMessage());
            toReturn = e;
        }
        catch(Exception e) {
            Log.e(MainActivity.class.getName(), "Error: " + e.getMessage());
            toReturn = e;
        }

        return toReturn;
    }

    @Override
    protected void onPostExecute(Exception exception) {
        onRequestTokenRetrieved(exception);
    }
 }

 private void onRequestTokenRetrieved(Exception result) {

     if (result != null) {
         Toast.makeText(
                 this, 
                 result.getMessage(), 
                 Toast.LENGTH_LONG
                 ).show();
     }

     else {
         try {
             // Shared Preferences
             Editor editor = mSharedPreferences.edit();

             // After getting access token, access token secret
             // store them in application preferences
             editor.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
             editor.putString(PREF_KEY_OAUTH_SECRET,
                     accessToken.getTokenSecret());
             // Store login status - true
             editor.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
             editor.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);
             follow.setVisibility(View.VISIBLE);
             // Getting user details from twitter
             String username = user.getName();

             // Displaying in xml ui
             lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
         }
         catch (Exception ex) {
             // Check log for login errors
             Log.e("Twitter Login Error", "> " + ex.getMessage());
             ex.printStackTrace();
         }
     }
 }

/**
 * Function to login twitter
 * */
private void loginToTwitter() {
    // Check if already logged in
    if (!isTwitterLoggedInAlready()) {
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
        builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        Configuration configuration = builder.build();

        TwitterFactory factory = new TwitterFactory(configuration);
        twitter = factory.getInstance();


            Thread thread = new Thread(new Runnable(){
                @Override
                public void run() {
                    try {
                        requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
                        MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));

                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(), "Already Logged into twitter", Toast.LENGTH_LONG).show();
                    }
                }
            });
            thread.start();         
    } else {
        // user already logged into twitter
        Toast.makeText(getApplicationContext(), "Already Logged into twitter", Toast.LENGTH_LONG).show();
    }
}

/**
 * Function to update status
 * */
class updateTwitterStatus extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Updating to twitter...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting Places JSON
     * */
    protected String doInBackground(String... args) {
        Log.d("Tweet Text", "> " + args[0]);
        String status = args[0];
        try {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
            builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);

            // Access Token 
            String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
            // Access Token Secret
            String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");

            AccessToken accessToken = new AccessToken(access_token, access_token_secret);
            Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

            // Update status
            twitter4j.Status response = twitter.updateStatus(status);

            Log.d("Status", "> " + response.getText());
        } catch (TwitterException e) {
            // Error in updating status
            Log.d("Twitter Update Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog and show
     * the data in UI Always use runOnUiThread(new Runnable()) to update UI
     * from background thread, otherwise you will get error
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(),
                        "Status tweeted successfully", Toast.LENGTH_SHORT)
                        .show();
                // Clearing EditText field
                txtUpdate.setText("");
            }
        });
    }
}

/**
 * Function to logout from twitter
 * It will just clear the application shared preferences
 * */
private void logoutFromTwitter() {
    // Clear the shared preferences
    Editor e = mSharedPreferences.edit();
    e.remove(PREF_KEY_OAUTH_TOKEN);
    e.remove(PREF_KEY_OAUTH_SECRET);
    e.remove(PREF_KEY_TWITTER_LOGIN);
    e.commit();

    // After this take the appropriate action
    // I am showing the hiding/showing buttons again
    // You might not needed this code
    btnLogoutTwitter.setVisibility(View.GONE);
    btnUpdateStatus.setVisibility(View.GONE);
    txtUpdate.setVisibility(View.GONE);
    lblUpdate.setVisibility(View.GONE);
    lblUserName.setText("");
    lblUserName.setVisibility(View.GONE);

    btnLoginTwitter.setVisibility(View.VISIBLE);
}

/**
 * Check user already logged in your application using twitter Login flag is
 * fetched from Shared Preferences
 * */
private boolean isTwitterLoggedInAlready() {
    // return twitter login status from Shared Preferences
    return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}

protected void onResume() {
    super.onResume();
}

1 个答案:

答案 0 :(得分:0)

首先尝试正常,因为:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    /**
     * Function to login twitter
     * */
    private void loginToTwitter() {
        // Check if already logged in
//      if (!isTwitterLoggedInAlready()) {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
            builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
            Configuration configuration = builder.build();

            TwitterFactory factory = new TwitterFactory(configuration);
            twitter = factory.getInstance();


                Thread thread = new Thread(new Runnable(){
                    @Override
                    public void run() {
                        try {
                            requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
                            MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));

                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(), "Already Logged into twitter", Toast.LENGTH_LONG).show();
                        }
                    }
                });
                thread.start();         
//      } else {
//          // user already logged into twitter
//          Toast.makeText(getApplicationContext(), "Already Logged into twitter", Toast.LENGTH_LONG).show();
//      }
    }


    public void btnAdd_Click(View v) {
        loginToTwitter();

    }

    public void btnAdd2_Click(View v) {
           try {
                Twitter twitter = new TwitterFactory().getInstance();
                twitter.createFriendship("Dan");
                System.out.println("Successfully followed [Dan].");
                System.exit(0);
            } catch (TwitterException te) {
                te.printStackTrace();
                System.out.println("Failed to follow: " + te.getMessage());
                System.exit(-1);
            }

    }