繁体   English   中英

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

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

我是android编程的新手,我正在尝试将自定义对象的数组发送到其他活动。 在第一个活动中,我有一个创建意图并向其中添加对象数组的函数:

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

但是,我不确定如何在下一个屏幕上获取该数据。

即使“任务”是自定义对象的数组,有没有办法在代码中为下一个活动获取该数组?

您是否曾与Gson尝试过?

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

在第二个活动中,将多余的数据解析回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