我想将Twitter会话从一个活动发送到另一个活动。我已经搜索了(How to pass an object from one activity to another on Android),但是可序列化的TwitterSession出现了错误。该方案是当用户成功登录时,此会话信息将转到MainActivity。这是我的代码。
我怎么了

TwitterSessionObject.java

import com.twitter.sdk.android.core.TwitterSession;
import java.io.Serializable;

public class TwitterSessionObject implements Serializable {

    private TwitterSession session;

    public TwitterSessionObject(TwitterSession twitterSession){

        this.session = twitterSession;
    }
    public TwitterSession getTwitterSession() {
        return session;
    }
    public void setSession(TwitterSession session) {
        this.session = session;
    }
}


Login.java

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
        Fabric.with(this, new Twitter(authConfig));
        setContentView(R.layout.activity_login);

        loginButton = (TwitterLoginButton) findViewById(R.id.twitter_login_button);
        loginButton.setCallback(new Callback<TwitterSession>() {
            @Override
            public void success(Result<TwitterSession> result) {
                // Do something with result, which provides a TwitterSession for making API calls

                TwitterSession session = Twitter.getSessionManager().getActiveSession();
                TwitterAuthToken authToken = session.getAuthToken();
                String token = authToken.token;
                String secret = authToken.secret;

                TwitterSessionObject sessionObject = new TwitterSessionObject(session);

                Intent intent = new Intent(Login.this, MainActivity.class);
                intent.putExtra("Session", sessionObject);
                startActivity(intent);
            }

            @Override
            public void failure(TwitterException exception) {
                // Do something on failure
            }
        });
    }


MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = getIntent();
        TwitterSessionObject session = (TwitterSessionObject)intent.getSerializableExtra("Session");
    }

最佳答案

你不能这样通过。 TwitterSession不可序列化,因此您不能使其成为可序列化类的成员。

由于TwitterSession是单例,因此您只需在MainActivity中调用以下方法

TwitterSession session = Twitter.getSessionManager().getActiveSession();


所以你的活动代码看起来像

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TwitterSession session = Twitter.getSessionManager().getActiveSession();

}

10-08 19:36