Android Class Parcelable with ArrayList

后端 未结 4 1116
太阳男子
太阳男子 2020-11-30 01:42

I have an android project where I have a class. In that class is an ArrayList. I will be getting some XML, parsing it out, then making objects ou

4条回答
  •  时光说笑
    2020-11-30 02:39

    Create a new java file for "Choices" and implement "Parcelable". If you do not implement parcelable you will get run-time exception (Unable to Marshal). So use the code below :

        public class Choices implements Parcelable{
    
            boolean isCorrect;
            String choice;
    
            public Choices(boolean isCorrect, String choice) {
                this.isCorrect = isCorrect;
                this.choice = choice;
            }
            //Create getters and setters 
    
            protected Choices(Parcel in) {
                isCorrect = in.readByte() != 0;
                choice = in.readString();
            }
    
            public static final Creator CREATOR = new Creator() {
                @Override
                public Choices createFromParcel(Parcel in) {
                    return new Choices(in);
                }
    
                @Override
                public Choices[] newArray(int size) {
                    return new Choices[size];
                }
            };
    
            @Override
            public String toString() {
                return "Choices [isCorrect=" + isCorrect + ", choice=" + choice
                        + "]";
            }
    
            @Override
            public int describeContents() {
                return 0;
            }
    
            @Override
            public void writeToParcel(Parcel dest, int flags) {
                dest.writeByte((byte) (isCorrect ? 1 : 0));
                dest.writeString(choice);
            }
        }
    

    As mentioned in above answer by @G.Blake you need to make Choices Parcelable and Android knows how to parcel ArrayLists of Parcelables

提交回复
热议问题