Android的反序列化对象? [英] android deserialize object?

查看:170
本文介绍了Android的反序列化对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何反序列化这种类型的:

how to deserialize this type:

public Intent putExtra(String name, Serializable value)

例如:

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

如何做到这一点,请;

how to do this please;

请帮助!

推荐答案

如果你想从一个活动传递一个自定义对象到另一个,首先你必须有你的自定义对象的类来实现的Java。 io.Serializable

If you want to pass a custom object from one activity to the other, first you must have your custom object's class to implement 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与你打电话给你新的活动的意图

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

在你的 GoToThisActivity 的onCreate 方法,你可以提取这个额外的:

Inside your GoToThisActivity class' onCreate method you can extract this extra as:

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

现在,你有你的新的活动你的自定义对象。

And now you have your custom object in your new activity.

更新1:传递一个类的其他活动与意图
如果你想要一个实例传递到意图:

Update 1: Passing a class to an other activity with Intent
If you want to pass a Class instance to an intent:

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

和反序列化是在其他活动:

and to deserialize it in the other activity:

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

更新2:
当反序列化的自定义对象的数组,你必须确保,在该数组中的元素贯彻序列化接口。

Update 2:
When deserializing an array of custom objects, you have to make sure, that the elements in that array implement the Serializable interface.

要留在你的样品:

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

您把额外的意图

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

和其他活动的内部反序列化:

And inside the other activity deserialize it:

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

您必须转换数组作为对象[] 不管原来的幸福 ButtonPicks []
数组内的元素都有其正确的类型,所以里面是

You MUST cast the array as Object[] regardless to the original being ButtonPicks[].
The elements inside the array have their proper type, so inside are the

{ButtonPicks.EDIT,ButtonPicks.DELETE}

{ ButtonPicks.EDIT, ButtonPicks.DELETE }

成员。
你需要分别扮演他们。

members.
You need to cast them individually.

这篇关于Android的反序列化对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆