Problem in Twitter integration on Android

左心房为你撑大大i 提交于 2020-01-13 05:48:08

问题


I follow this link site to integrate Twitter on Android.
But the problem is my consumer key and secret have some problem because when I run my application it gives the Sorry! your application has stopped unexpectedly error and when I checked in logcat it's giving null pointer exception

my logcat result is

07-07 11:06:50.962: ERROR/AndroidRuntime(323): java.lang.RuntimeException: Unable to resume activity {com.ecs.android.sample.twitter/com.ecs.android.sample.twitter.AndroidTwitterSample}: java.lang.NullPointerException
07-07 11:06:50.962: ERROR/AndroidRuntime(323):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3128)
07-07 11:06:50.962: ERROR/AndroidRuntime(323):     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3143)
07-07 11:06:50.962: ERROR/AndroidRuntime(323):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2684)
07-07 11:06:50.962: ERROR/AndroidRuntime(323):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-07 11:06:50.962: ERROR/AndroidRuntime(323):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-07 11:06:50.962: ERROR/AndroidRuntime(323):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-07 11:06:50.962: ERROR/AndroidRuntime(323): Caused by: java.lang.NullPointerException
07-07 11:06:50.962: ERROR/AndroidRuntime(323):     at com.ecs.android.sample.twitter.TwitterUtils.isAuthenticated(TwitterUtils.java:18)
07-07 11:06:50.962: ERROR/AndroidRuntime(323):     at com.ecs.android.sample.twitter.AndroidTwitterSample.updateLoginStatus(AndroidTwitterSample.java:67)
07-07 11:06:50.962: ERROR/AndroidRuntime(323):     at com.ecs.android.sample.twitter.AndroidTwitterSample.onResume(AndroidTwitterSample.java:63)
07-07 11:06:50.962: ERROR/AndroidRuntime(323):     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1149)
07-07 11:06:50.962: ERROR/AndroidRuntime(323):     at android.app.Activity.performResume(Activity.java:3823)
07-07 11:06:50.962: ERROR/AndroidRuntime(323):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3118)

Please tell me what is the mistake I am making?

And the whole code with 5 classes is:

Constants class- package com.ecs.android.sample.twitter;

package com.ecs.android.sample.twitter;

public class Constants {

    public static final String CONSUMER_KEY = "consumer key";
    public static final String CONSUMER_SECRET= "consumer secret key";

    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  CALLBACK_SCHEME = "x-oauthflow-twitter";
    public static final String  CALLBACK_HOST = "callback";
    public static final String  CALLBACK_URL = CALLBACK_SCHEME + "://" + CALLBACK_HOST;
}

AndroidTwitterSample Class -

public class AndroidTwitterSample extends Activity {

    private SharedPreferences prefs;
    private final Handler mTwitterHandler = new Handler();
    private TextView loginStatus;

    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);
        Button tweet = (Button) findViewById(R.id.btn_tweet);
        Button clearCredentials = (Button) findViewById(R.id.btn_clear_credentials);

        tweet.setOnClickListener(new View.OnClickListener() {
            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 "Tweeting from Android App at " + new Date().toLocaleString();
    }   

    public void sendTweet() {
        Thread t = new Thread() {
            @Override
            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();
    }
}

Twitter Utils Class -

import oauth.signpost.OAuth;
import twitter4j.Twitter;
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, "");

        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 (Exception 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, "");

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

OAuthRequestToken Class-

public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> {

    final String TAG = getClass().getName();
    private Context context;
    private OAuthProvider provider;
    private OAuthConsumer consumer;


    public OAuthRequestTokenTask(Context context,OAuthConsumer consumer,OAuthProvider provider) {
        this.context = context;
        this.consumer = consumer;
        this.provider = provider;
    }

    public OAuthRequestTokenTask(PrepareRequestTokenActivity context2,
            CommonsHttpOAuthConsumer consumer2,
            CommonsHttpOAuthProvider provider2) {
        // TODO Auto-generated constructor stub
    }


    @Override
    protected Void doInBackground(Void... params) {

        try {
            Log.i(TAG, "Retrieving request token from Google servers");
            final String url = provider.retrieveRequestToken(consumer, Constants.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;
    }
}

PrepareRequestTokenActivity Class-

public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> {

    final String TAG = getClass().getName();
    private Context context;
    private OAuthProvider provider;
    private OAuthConsumer consumer;

    public OAuthRequestTokenTask(Context context,OAuthConsumer consumer,OAuthProvider provider) {
        this.context = context;
        this.consumer = consumer;
        this.provider = provider;
    }

    public OAuthRequestTokenTask(PrepareRequestTokenActivity context2,
            CommonsHttpOAuthConsumer consumer2,
            CommonsHttpOAuthProvider provider2) {
        // TODO Auto-generated constructor stub
    }


    @Override
    protected Void doInBackground(Void... params) {

        try {
            Log.i(TAG, "Retrieving request token from Google servers");
            final String url = provider.retrieveRequestToken(consumer, Constants.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;
    }
}

回答1:


You have to put CONSUMER_KEY = "enter consumer key here" and CONSUMER_SECRET="enter consumer secret here" in your Constants class. For that you have to register your application in Twitter. To register your app, visit https://dev.twitter.com/user . After that it will give you those keys.



来源:https://stackoverflow.com/questions/6606678/problem-in-twitter-integration-on-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!