无法登录Twitter并通过我的应用程序共享文本

时间:2013-08-30 07:14:07

标签: java android twitter mobile-application

每当我在我的应用程序中点击Twitter的登录按钮时,它会将我带到webview,在那里它要求获得应用程序的授权,但是当我尝试共享文本时,它会显示以下给出的错误... ..ie(空指针异常)..我已经给出了下面的logcat以及我找到错误的代码。

logcat的

08-30 06:55:10.539: E/AndroidRuntime(1308):     at com.Background_fb_twitter.share_text$2.onClick(share_text.java:55)
08-30 07:05:01.330: E/AndroidRuntime(1680): FATAL EXCEPTION: main
08-30 07:05:01.330: E/AndroidRuntime(1680): java.lang.NullPointerException
08-30 07:05:01.330: E/AndroidRuntime(1680):     at com.Background_fb_twitter.share_text.postToWall(share_text.java:75)
08-30 07:05:01.330: E/AndroidRuntime(1680):     at com.Background_fb_twitter.share_text$2.onClick(share_text.java:55)
08-30 07:05:01.330: E/AndroidRuntime(1680):     at android.view.View.performClick(View.java:4204)
08-30 07:05:01.330: E/AndroidRuntime(1680):     at android.view.View$PerformClick.run(View.java:17355)
08-30 07:05:01.330: E/AndroidRuntime(1680):     at android.os.Handler.handleCallback(Handler.java:725)
08-30 07:05:01.330: E/AndroidRuntime(1680):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-30 07:05:01.330: E/AndroidRuntime(1680):     at android.os.Looper.loop(Looper.java:137)
08-30 07:05:01.330: E/AndroidRuntime(1680):     at android.app.ActivityThread.main(ActivityThread.java:5041)
08-30 07:05:01.330: E/AndroidRuntime(1680):     at java.lang.reflect.Method.invokeNative(Native Method)
08-30 07:05:01.330: E/AndroidRuntime(1680):     at java.lang.reflect.Method.invoke(Method.java:511)
08-30 07:05:01.330: E/AndroidRuntime(1680):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-30 07:05:01.330: E/AndroidRuntime(1680):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-30 07:05:01.330: E/AndroidRuntime(1680):     at dalvik.system.NativeStart.main(Native Method)

Background_fb_Activity

package com.Background_fb_twitter;


import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class Background_fb_twitterActivity extends Activity {
    private Button btn_fb;
    private Button btn_tw;
    private Button btn_share;

    /** face book details */
    static final String APP_ID = "XXXXXXXXXX";
    static final String[] PERMISSIONS = new String[] { "publish_stream" };
    static final String TOKEN = "1685102257-7K2lwqoBlgi1xifnZGOoWbZPLAHHVyNFlLwW6iZ";
    static final String EXPIRES = "expires_in";
    static final String KEY = "facebook-credentials";
    static Facebook facebook1;
    private boolean FB_LOGIN = false;

    /** ---------------------------------- */

    private boolean TWEET = false;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn_fb = (Button) findViewById(R.id.btn_fb);
        btn_tw = (Button) findViewById(R.id.btn_twitter);
        btn_share = (Button) findViewById(R.id.btn_share);

        btn_fb.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                facebook1 = new Facebook(APP_ID);
                loginAndPostToWall();
            }
        });

        btn_tw.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(getApplicationContext(),
                        PrepareRequestTokenActivity.class);
                i.putExtra("tweet_msg", "");
                startActivity(i);
                TWEET = true;
            }
        });

        btn_share.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                startActivity(new Intent(Background_fb_twitterActivity.this, share_text.class));
                /*if (FB_LOGIN && TWEET) {
                    //show_alert();

                }
                else
                {
                    Toast.makeText(Background_fb_twitterActivity.this,
                            "Pleaes Login To facebook & Twitter!", Toast.LENGTH_SHORT)
                            .show();
                }*/
            }
        });
    }



    /** facebook methods---------------------------------------------start */
    public void loginAndPostToWall() {
        facebook1.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH,
                new LoginDialogListener());

    }

    class LoginDialogListener implements DialogListener {

        public void onComplete(Bundle values) {
            saveCredentials(facebook1);
            FB_LOGIN = true;
        }

        public void onFacebookError(FacebookError error) {
            showToast("Authentication with Facebook failed!");
        }

        public void onError(DialogError error) {
            showToast("Authentication with Facebook failed!");
        }

        public void onCancel() {
            showToast("Authentication with Facebook cancelled!");
        }
    }

    private void showToast(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT)
                .show();
    }

    public boolean saveCredentials(Facebook facebook) {

        Editor editor = getApplicationContext().getSharedPreferences(KEY,
                Context.MODE_PRIVATE).edit();
        editor.putString(TOKEN, facebook.getAccessToken());
        editor.putLong(EXPIRES, facebook.getAccessExpires());
        return editor.commit();
    }

    public boolean restoreCredentials(Facebook facebook) {
        SharedPreferences sharedPreferences = getApplicationContext()
                .getSharedPreferences(KEY, Context.MODE_PRIVATE);

        facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
        facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
        return facebook.isSessionValid();
    }

    /** facebook methods---------------------------------------------end */


}

Share_text.java ..(此文件中的错误Iam得到)。

package com.Background_fb_twitter;


import com.facebook.android.Facebook;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class share_text extends Activity {

    private EditText edit;
    private Button btns;

    /** face book details */
    static final String APP_ID = "XXXXXXXXXX";
    static final String[] PERMISSIONS = new String[] { "publish_stream" };
    static final String TOKEN = "access_token";
    static final String EXPIRES = "expires_in";
    static final String KEY = "facebook-credentials";
    static Facebook facebook1;
    private boolean FB_LOGIN = false;

    /** ---------------------------------- */

    private SharedPreferences prefs1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.share_alert);
        this.prefs1 = PreferenceManager.getDefaultSharedPreferences(this);

        edit = (EditText) findViewById(R.id.editText1);
        btns = (Button) findViewById(R.id.button1);
        btns.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String str = edit.getText().toString();
                if (str != "") {

                    postToWall(str, share_text.this);

                    if (TwitterUtils.isAuthenticated(prefs1)) {
                    sendTweet(share_text.this, str);
                    }

                } else {
                    edit.setError("Please Enter Text!");
                }

            }
        });
    }

    public static void postToWall(String message, Context con) {
        facebook1 = new Facebook(APP_ID);
        String st = get_token__(con);
        Bundle parameters = new Bundle();
        parameters.putString("message", message);
        parameters.putString("description", "topic share");
        if (st.length() > 0) {
            parameters.putString("access_token", "" + st);
        }
        try {
            facebook1.request("me");
            String response = facebook1.request("me/feed", parameters, "POST");
            Log.d("Tests--->*************", "got response: " + response);

            if (response == null
                    || response.equals("")
                    || response.equals("false")
                    || response
                            .equalsIgnoreCase("{\"error\":{\"message\":\"An active access token must be used to query information about the current user.\",\"type\":\"OAuthException\",\"code\":2500}}")) {
                showToast("Blank response. please loginf again in facebook",
                        con);
                clear_fb_data(con);
            } else {
                showToast("Message posted to your facebook wall!", con);
            }
        } catch (Exception e) {
            showToast("Failed to post to wall!", con);
            e.printStackTrace();
        }
    }

    private static String get_token__(Context con) {
        // TODO Auto-generated method stub
        SharedPreferences sharedPreferences = con.getSharedPreferences(KEY,
                Context.MODE_PRIVATE);
        return sharedPreferences.getString(TOKEN, null);
    }

    private static void clear_fb_data(Context con) {
        // TODO Auto-generated method stub
        SharedPreferences se = PreferenceManager
                .getDefaultSharedPreferences(con);
        Editor editor = se.edit();
        editor.remove(TOKEN);
        editor.remove(EXPIRES);
        editor.commit();
    }

    private static void showToast(String message, Context con) {
        Toast.makeText(con, message, Toast.LENGTH_SHORT).show();
    }

    /** twitter methods-------------------------- start */

    private final static Handler mTwitterHandler = new Handler();
    private static SharedPreferences prefs;

    public static boolean TWEET_LOGIN = false;

    final static Runnable mUpdateTwitterNotification = new Runnable() {
        public void run() {

        }
    };

    public static void sendTweet(Context con, final String msj) {

        prefs = PreferenceManager.getDefaultSharedPreferences(con);

        Thread t = new Thread() {
            public void run() {

                try {
                    TwitterUtils.sendTweet(prefs, msj);
                    mTwitterHandler.post(mUpdateTwitterNotification);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    Log.d("dhaval-->send tweet:", ex.getMessage().toString());
                }
            }

        };
        t.start();
    }

    /** twitter methods-------------------------- end */
}

Constants.java

package com.Background_fb_twitter;

public class Constants {

    public static final String CONSUMER_KEY = "XXXXXXXX";
    public static final String CONSUMER_SECRET= "XXXXXXXX";

    public static final String REQUEST_URL = "https://api.twitter.com/oauth/request_token";
    public static final String ACCESS_URL = "https://api.twitter.com/oauth/access_token";
    public static final String AUTHORIZE_URL = "https://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;

}

2 个答案:

答案 0 :(得分:0)

问题是,你在这一行上遇到了NullPointerException,

 String st = get_token__(con);

这里String st似乎是null。这是因为,方法get_token__(con);返回空值。

如果您查看此方法,您将从共享首选项中获取值,但作为默认值,您将获得null,

  private static String get_token__(Context con) {
        // TODO Auto-generated method stub
        SharedPreferences sharedPreferences = con.getSharedPreferences(KEY,
                Context.MODE_PRIVATE);
        return sharedPreferences.getString(TOKEN, null); // This returns null..
    }

由于String st为null,因此length()无法执行并抛出NullPointerException。

答案 1 :(得分:0)

更改此方法:如果您使用此代码登录Twitter,只需检查日志即可获得访问令牌。

private static String get_token__(Context con) {
        // TODO Auto-generated method stub
        SharedPreferences sharedPreferences = con.getSharedPreferences(KEY,
                Context.MODE_PRIVATE);
        return sharedPreferences.getString(OAuth.OAUTH_TOKEN, "");
    }

如果上述方法不起作用,那么只需将access token放入prefrence n用于上述方法。