How to read/write a boolean when implementing the Parcelable interface?

后端 未结 12 1242
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 14:33

I\'m trying to make an ArrayList Parcelable in order to pass to an activity a list of custom object. I start writing a myObjectList cl

相关标签:
12条回答
  • 2020-11-29 15:06

    You could pack your boolean values into a byte using masking and shifting. That would be the most efficient way to do it and is probably what they would expect you to do.

    0 讨论(0)
  • 2020-11-29 15:07

    You could also make use of the writeValue method. In my opinion that's the most straightforward solution.

    dst.writeValue( myBool );
    

    Afterwards you can easily retrieve it with a simple cast to Boolean:

    boolean myBool = (Boolean) source.readValue( null );
    

    Under the hood the Android Framework will handle it as an integer:

    writeInt( (Boolean) v ? 1 : 0 );
    
    0 讨论(0)
  • 2020-11-29 15:09

    It is hard to identify the real question here. I guess it is how to deal with booleans when implementing the Parcelable interface.

    Some attributes of MyObject are boolean but Parcel don't have any method read/writeBoolean.

    You will have to either store the value as a string or as a byte. If you go for a string then you'll have to use the static method of the String class called valueOf() to parse the boolean value. It isn't as effective as saving it in a byte tough.

    String.valueOf(theBoolean);
    

    If you go for a byte you'll have to implement a conversion logic yourself.

    byte convBool = -1;
    if (theBoolean) {
        convBool = 1;
    } else {
        convBool = 0;
    }
    

    When unmarshalling the Parcel object you have to take care of the conversion to the original type.

    0 讨论(0)
  • 2020-11-29 15:10

    There are many examples in the Android (AOSP) sources. For example, PackageInfo class has a boolean member requiredForAllUsers and it is serialized as follows:

    public void writeToParcel(Parcel dest, int parcelableFlags) {
        ...
        dest.writeInt(requiredForAllUsers ? 1 : 0);
        ...
    }
    
    private PackageInfo(Parcel source) {
        ...
        requiredForAllUsers = source.readInt() != 0;
        ...
    }
    
    0 讨论(0)
  • 2020-11-29 15:13

    you declare like this

     private boolean isSelectionRight;
    

    write

     out.writeInt(isSelectionRight ? 1 : 0);
    

    read

    isSelectionRight  = (in.readInt() == 0) ? false : true;
    

    boolean type needs to be converted to something that Parcel supports and so we can convert it to int.

    0 讨论(0)
  • 2020-11-29 15:13

    I normally have them in an array and call writeBooleanArray and readBooleanArray

    If it's a single boolean you need to pack, you could do this:

    parcel.writeBooleanArray(new boolean[] {myBool});
    
    0 讨论(0)
提交回复
热议问题