我是 Android 编程新手,我正在尝试将一组自定义对象发送到不同的 Activity 。在第一个 Activity 中,我有一个函数,它创建一个 Intent 并向其中添加对象数组:
public void openSchedule() {
Intent nextScreen = new Intent(getApplicationContext(), Schedule.class);
nextScreen.putExtra("array", tasks);
startActivity(nextScreen);
}
但是,我不确定如何在下一个屏幕上获取该数据。
即使“任务”是自定义对象的数组,是否有任何方法可以在下一个 Activity 的代码中获取该数组?
最佳答案
你尝试过Gson吗? ?
public void openSchedule() {
Intent nextScreen = new Intent(getApplicationContext(), Schedule.class);
String arrayAsString = new Gson().toJson(tasks);
nextScreen.putExtra("array", arrayAsString);
startActivity(nextScreen);
}
在第二个 Activity 中,将额外的数据解析回 List<T>
public void parseBack(){
String arrayAsString = getIntent().getExtras().getString("array");
List<YourType> list = Arrays.asList(new Gson().fromJson(arrayAsString, YourType[].class));
}
关于java - 将自定义对象数组传递给 android 中的另一个 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31613053/