How to send non-string data across activity

こ雲淡風輕ζ 提交于 2019-12-24 18:41:30

问题


In twitterfragment class I have

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 

In twitter_timeline class I want to get the statues I sent from twitter fragment.

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
    }

Here intent expects to get StringArray in the function getIntent.getStringArrayExtra(...), but I have sent Twitter Status from my fragment.


回答1:


Because the twitter4j.Status class implements Serializable, you should be able to create a Serializable wrapper class and send that through the Intent Extras.

Create a MyStatuses class in MyStatuses.java:

import java.io.Serializable;

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

Then send an instance of the wrapper class in the 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);

Then use getSerializable() in order to get the 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;
        }
    }


来源:https://stackoverflow.com/questions/31421465/how-to-send-non-string-data-across-activity

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