我无法在android中获取twitter的访问令牌

时间:2013-11-24 12:37:46

标签: android twitter token

我在应用程序中将twitter集成到登录和推文时面临很大问题 我无法获得access_token,我用Google搜索了很长时间,我现在很沮丧

Logcat向我显示此行中的错误

e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());  从twitter重定向时

注意:我使用的是twitter4j-core-3.0.5.jar,我按照的教程是twitter4j-core-3.0.3.jar

我希望你能帮助我,因为我真的遇到麻烦了

这是我的代码: -

package com.engahmedphp.successquotes;

import java.io.File;

import twitter4j.Twitter;
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.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.util.Log;
import android.widget.TimePicker;
import android.widget.Toast;

public class SettingsActivity extends PreferenceActivity {
    private int hour;
    private int minute;

    static final int TIME_DIALOG_ID = 999;

    static String TWITTER_CONSUMER_KEY = "9b5e5CKWI3SbSJ4HoVnsMA";
    static String TWITTER_CONSUMER_SECRET = "igj0dTYlPVygRddnklhvluOtiA7W8HySCjOsyq6Vo";

    // 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://com.engahmedphp.successquotes.SettingsActivity";

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

    // Progress dialog
    ProgressDialog pDialog;

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

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

        addPreferencesFromResource(R.layout.settings);
        setTitle("Settings");
        final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

        cd = new ConnectionDetector(getApplicationContext());

        // Check if Internet present
        if (!cd.isConnectingToInternet()) {
            // Internet Connection is not present
            alert.showAlertDialog(SettingsActivity.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(SettingsActivity.this, "Twitter oAuth tokens",
                    "Please set your twitter oauth tokens first!", false);
            // stop executing code by return
            return;
        }

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

        Preference notify_me = (Preference) findPreference("notify_me");
        final Preference time = (Preference) findPreference("time");
        Preference background = (Preference) findPreference("background");
        Preference facebook = (Preference) findPreference("facebook_login");
        Preference twitter_login = (Preference) findPreference("twitter_login");
        Preference twitter_logout = (Preference) findPreference("twitter_logout");
        Preference about = (Preference) findPreference("about");

        boolean notify_me_value = sharedPrefs.getBoolean("notify_me", true);
        boolean background_value = sharedPrefs.getBoolean("background", false);

        // ==============================================================================

        time.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {

                showDialog(TIME_DIALOG_ID);

                return true;
            }
        });

        twitter_login.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {

                loginToTwitter();

                return false;
            }
        });

        twitter_logout.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {



                return true;
            }
        });

        if (!isTwitterLoggedInAlready()) {
            Uri uri = getIntent().getData();
            if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
                // oAuth verifier
                final String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

                try {

                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {

                                // Get the access token
                                SettingsActivity.this.accessToken = twitter.getOAuthAccessToken(requestToken, verifier);

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    thread.start();

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

                    // 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());
                    e.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);
                        SettingsActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken
                                .getAuthenticationURL())));

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
        } 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);
    }


    // ==============================================================================

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case TIME_DIALOG_ID:
            // set time picker as current time
            return new TimePickerDialog(this, timePickerListener, hour, minute, false);

        }
        return null;
    }

    // ==============================================================================

    private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
            hour = selectedHour;
            minute = selectedMinute;

        }
    };

    // ==============================================================================

    @Override
    protected void onPause() {
        super.onPause();
    }

    // ==============================================================================

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

}

logcat的

11-24 07:28:05.230: E/Twitter Login Error(2068): > null
11-24 07:28:05.249: W/System.err(2068): java.lang.NullPointerException
11-24 07:28:05.249: W/System.err(2068):     at com.engahmedphp.successquotes.SettingsActivity.onCreate(SettingsActivity.java:172)
11-24 07:28:05.269: W/System.err(2068):     at android.app.Activity.performCreate(Activity.java:5133)
11-24 07:28:05.269: W/System.err(2068):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-24 07:28:05.279: W/System.err(2068):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-24 07:28:05.289: W/System.err(2068):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-24 07:28:05.299: W/System.err(2068):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-24 07:28:05.299: W/System.err(2068):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-24 07:28:05.319: W/System.err(2068):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-24 07:28:05.319: W/System.err(2068):     at android.os.Looper.loop(Looper.java:137)
11-24 07:28:05.363: W/System.err(2068):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-24 07:28:05.363: W/System.err(2068):     at java.lang.reflect.Method.invokeNative(Native Method)
11-24 07:28:05.363: W/System.err(2068):     at java.lang.reflect.Method.invoke(Method.java:525)
11-24 07:28:05.382: W/System.err(2068):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-24 07:28:05.389: W/System.err(2068):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-24 07:28:05.389: W/System.err(2068):     at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

我终于明白了。我移动这段代码:

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

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

在线程中就像那样

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

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

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

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();