如何跨活动发送非字符串数据

时间:2015-07-15 04:23:10

标签: java android android-fragments android-activity twitter4j

在twitterfragment课程中我有

List<twitter4j.Status> statuses = twitter.getUserTimeline(user);
Intent intent = new Intent(getActivity(), twitter_timeline.class);
intent.putExtra(twitter_timeline.STATUS_LIST, statuses);// this line giving error if I pass status 

在twitter_timeline课程中,我想获得我从twitter片段发送的雕像。

public class twitter_timeline extends Activity {
    public static List<twitter4j.Status> STATUS_LIST;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_twitter_timeline);

        setTitle("Timeline");

        List<twitter4j.Status> statuses = (Status) this.getIntent().getStringArrayExtra(STATUS_LIST); // this line not resolving even if I cast it to status type
    }

这里intent希望在函数getIntent.getStringArrayExtra(...)中获取StringArray,但我已从我的片段中发送了Twitter状态。

1 个答案:

答案 0 :(得分:1)

因为twitter4j.Status类实现了Serializable,所以你应该能够创建一个Serializable包装类并通过Intent Extras发送它。

在MyStatuses.java中创建一个MyStatuses类:

import java.io.Serializable;

public class MyStatuses implements Serializable {
    List<twitter4j.Status> statuses;
}

然后在Intent Extras中发送包装类的实例:

    List<twitter4j.Status> statuses = twitter.getUserTimeline(user);
    MyStatuses myStatuses = new MyStatuses();
    myStatuses.statuses = statuses;
    Intent intent = new Intent(getActivity(), twitter_timeline.class);
    intent.putExtra("statuses", myStatuses);

然后使用getSerializable()来获取Intent Extra:

public class twitter_timeline extends Activity {
    //public static List<twitter4j.Status> STATUS_LIST; 
    List<twitter4j.Status> statuses;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_twitter_timeline);

        setTitle("Timeline");
        Bundle b = this.getIntent().getExtras();
        if (b != null) {
            MyStatuses myStatuses = (MyStatuses) b.getSerializable("statuses");
            statuses = myStatuses.statuses;
        }
    }