【问题标题】:Passing a custom Object from one Activity to another Parcelable vs Bundle将自定义对象从一个活动传递到另一个 Parcelable vs Bundle
【发布时间】:2012-09-04 00:24:33
【问题描述】:

我想将一个自定义对象从一个活动传递到另一个活动,该对象由一个字符串和另一个自定义对象的列表组成,该对象由一个字符串数组和一个整数数组组成。我读过https://stackoverflow.com/a/2141166/830104,但后来我找到了这个答案https://stackoverflow.com/a/7842273/830104。使用 Bundle 或 Parcelable 哪个更好?有什么区别?我应该什么时候使用这个?
感谢您的回复,

【问题讨论】:

  • 如果您的对象仅包含字符串、字符串数组和整数数组,那么只需使类可序列化并在启动下一个Activity 时使用IntentputExtra(String name, Serializable value) 方法。

标签: android android-intent android-activity


【解决方案1】:

ParcelableBundle 不是专有概念;您甚至可以同时在您的应用程序上部署两者。

[1] 术语Parcelable 带有Java 中的序列化概念(以及其他高级语言,如C#、Python 等)。它确保可以将此类 Parcelable 类的对象(保留在 RAM 存储中)保存在文件流中,例如文本或内存(离线状态),然后可以重构以在程序中使用运行时(在线状态)。

在 Android 应用程序中,在 2 个 independent activities 内(仅运行 - 一个启动,然后另一个必须停止):

当前活动不会有指向前一个活动及其成员的指针 - 因为前一个活动已停止并清除了表单内存;为了维护传递给下一个活动的对象值(从Intent 调用),对象需要是parcelable (serializable)。

[2]而Bundle通常是Android的概念,表示一个变量或一组变量。再往下看,可以认为是键值对的HashMap。

结论:

  • Bundle是存储很多对象,有相关的key,可以保存任何native类型的对象,但是不知道怎么保存一个复杂对象(例如包含一个ArrayList)

  • Parcelable 类是为了确保它的复杂实例在运行时可以是 serializedde-serialized .这个对象可以包含复杂的类型,比如ArrayList、HashMap、array,或者struct,...

[已更新] - 示例:

//Class without implementing Parcelable will cause error 
//if passing though activities via Intent
public class NoneParcelable
{
    private ArrayList<String> nameList = new ArrayList<String>();
    public NoneParcelable()
    {
        nameList.add("abc");
        nameList.add("xyz");            
    }
}

//Parcelable Class's objects can be exchanged 
public class GoodParcelable implements Parcelable
{
    private ArrayList<String> nameList = new ArrayList<String>();
    public GoodParcelable()
    {
        nameList.add("Can");
        nameList.add("be parsed");          
    }
    @Override
    public int describeContents()
    {
        return 0;
    }
    @Override
    public void writeToParcel(Parcel dest, int flags)
    {
        // Serialize ArrayList name here            
    }
}

在源活动中:

NoneParcelable nonePcl = new NoneParcelable();
GoodParcelable goodPcl = new GoodParcelable();
int count = 100;

Intent i = new Intent(...);
i.putExtra("NONE_P",nonePcl);
i.putExtra("GOOD_P",goodPcl);
i.putExtra("COUNT", count);

在目标活动中:

Intent i = getIntent();

//this is BAD:
NoneParcelable nP = (NoneParcelable)i.getExtra("NONE_P"); //BAD code

//these are OK:
int count = (int)i.getExtra("COUNT");//OK
GoodParcelable myParcelableObject=(GoodParcelable)i.getParcelableExtra("GOOD_P");// OK

【讨论】:

  • 其实Bundle是Parcelable的具体实现。通过简单地从对象的数据创建一个 Bundle 对象并使用 intent.putExtra("myObj", myObj.toBundle()) / MyObjecet.fromBundle(intent.getBundleExtra("myObj")) 来存储,您可以避免可怕的 Parcelable 接口/取回它。您必须自己实现 toBundle()/fromBundle(),类似于将对象属性存储到 hashmap 中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-26
  • 2013-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多