android nested object parceling

主宰稳场 提交于 2019-12-23 18:03:03

问题


how can we parcel nested object in an intent?.
For example lets say there is an object A which contain one string variable and one another object B. now B contain object C . C contain a list of string. so how i can parcel object A in an intent.
any help on this will be appreciated.
thanks in advance.

Implementation:

public static class A 
{
    private B  ObjectB;
}

public static class B 
{
    private String type;
    private List<C> C;
}

public static class C 
{
    private List<D> D;
}

public static class D 
{
    private String id;
    private String name;
    private String address;
    private String email;
}

how to write parcelable for class C. i am using

dest.writeParceable(ObjectC,flag)

For reading:

in.readParcelable(C.getClass().getClassLoader());

but its not working


回答1:


You would have to implement parcelable for object B and then implement parcelable for object A. I have never done this but the above should work.

Edit

See the code snippets below which illustrates how to implement parcelable for Class C.

  1. First implement parcelable for Class D like so:

    dest.writeString(id); 
    dest.writeString(name);  
    dest.writeString(address);  
    dest.writeString(email);
    
    id = in.readString();  
    name = in.readString();  
    address = in.readString();  
    email = in.readString();  
    
  2. Then implement parcelable for Class C as follows:

    dest.writeList(D);
    
    in.readList(D,this.getClass().getClassLoader());
    

This is untested code as I have never implemented nested parceling but worth a try. Hope that helps.




回答2:


One way I have seen this done is using serializeable

eg.

if you have a variable:

Date createdAt;

Then in writeToParcel(Parcel out, int flags) you can write:

out.writeSerializable(createdAt); 

To read the value back yoy would use:

createdAt = (Date) in.readSerializable();

That being said though Parcelable was specifically created because Java serialization was considered too slow. So while this works it is not a good idea to use for larger pieces of data.



来源:https://stackoverflow.com/questions/6642874/android-nested-object-parceling

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!