gpt4 book ai didi

android反序列化对象?

转载 作者:太空狗 更新时间:2023-10-29 15:39:43 28 4
gpt4 key购买 nike

如何反序列化这个类型:

public Intent putExtra(String name, Serializable value)

例子:

 intent.putExtra("activityToPass", GoToThisActivity.class);
???
getIntent().getExtras.getSerializable("activityToPass");

请问如何做到这一点;

请帮忙!!

最佳答案

如果您想将自定义对象从一个 Activity 传递到另一个 Activity ,首先您必须让自定义对象的类实现 java.io.Serializable:

public class SomeObject implements Serializable {
private String name;
public SomeObject (final String name) {
this.name = name;
}
[...]
}

final SomeObject myExtra = new SomeObject("any name");

然后您可以将此 myExtra 添加到调用新 Activity 的 Intent 中:

final Intent intent = new Intent(this, GoToThisActivity.class);
intent.putExtra("serializedExtra", myExtra);
startActivity(intent);

在您的 GoToThisActivity 类的 onCreate 方法中,您可以将此额外内容提取为:

final Intent intent = getIntent();
if (intent.hasExtra("serializedExtra"))
final SomeObject myExtra= (SomeObject)intent.
getSerializableExtra("serializedExtra");
[...]
}

现在您的新 Activity 中有了您的自定义对象。

更新 1:使用 Intent 将类传递给其他 Activity
如果你想将一个 Class 实例传递给一个 intent:

intent.putExtra("classExtra", GoToThisActivity.class);

并在另一个 Activity 中反序列化它:

if (intent.hasExtra("classExtra"))
{
final Class<?> classExtra= (Class<?>)intent.
getSerializableExtra("classExtra");
[...]
}

更新 2:
反序列化自定义对象数组时,您必须确保该数组中的元素实现了 Serializable 接口(interface)。

留在你的 sample 上:

public class ButtonPick implements Serializable
{
public static final ButtonPick EDIT = new ButtonPick();
public static final ButtonPick DELETE = new ButtonPick();
}

你把额外的放在Intent中:

intent.putExtra("buttonPicks", new ButtonPick[]
{ButtonPick.DELETE,ButtonPick.EDIT});

在另一个 Activity 中反序列化它:

if (intent.hasExtra("buttonPicks"))
{
final Object[] buttonPicks= (Object[])intent.
getSerializableExtra("buttonPicks");
[...]
}

无论原始数组是 ButtonPicks[],您都必须将数组转换为 Object[]
数组中的元素有它们正确的类型,所以里面是

{ ButtonPicks.EDIT, ButtonPicks.DELETE }

成员。
您需要单独转换它们。

关于android反序列化对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5866093/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com