简体   繁体   English

将自定义对象数组传递给android中的另一个Activity

[英]Pass array of custom objects to another Activity in android

I am new to android programming, and I am trying to send an array of custom objects to a different activity. 我是android编程的新手,我正在尝试将自定义对象的数组发送到其他活动。 In the first activity I have a function that creates an intent and adds the array of objects to it: 在第一个活动中,我有一个创建意图并向其中添加对象数组的函数:

public void openSchedule() {
    Intent nextScreen = new Intent(getApplicationContext(), Schedule.class);
    nextScreen.putExtra("array", tasks);
    startActivity(nextScreen);
}

However, I'm not sure how to get that data at the next screen. 但是,我不确定如何在下一个屏幕上获取该数据。

Is there any way to get that array in the code for the next activity even though "tasks" is an array of custom objects? 即使“任务”是自定义对象的数组,有没有办法在代码中为下一个活动获取该数组?

Did you try it with Gson ? 您是否曾与Gson尝试过?

public void openSchedule() {
    Intent nextScreen = new Intent(getApplicationContext(), Schedule.class);
    String arrayAsString = new Gson().toJson(tasks);
    nextScreen.putExtra("array", arrayAsString);
    startActivity(nextScreen);
}

In your second activity, parse the extra data back into the List<T> 在第二个活动中,将多余的数据解析回List<T>

public void parseBack(){
    String arrayAsString = getIntent().getExtras().getString("array");
    List<YourType> list = Arrays.asList(new Gson().fromJson(arrayAsString, YourType[].class));
}

让你的自定义对象实现Parcelable ,为了利用putParcelableArrayListExtraIntent类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM