How to serialize null value when using Parcelable interface

前端 未结 4 599
抹茶落季
抹茶落季 2020-12-08 09:35

regarding my code example down, what shold I do if one Locable\'s variables is null? In example, now if l.getZoom() returns null, I got NullPointerException.



        
4条回答
  •  一整个雨季
    2020-12-08 10:01

    This is the solution I came up with to write strings safely:

    private void writeStringToParcel(Parcel p, String s) {
        p.writeByte((byte)(s != null ? 1 : 0));
        p.writeString(s);
    }
    
    private String readStringFromParcel(Parcel p) {
        boolean isPresent = p.readByte() == 1;
        return isPresent ? p.readString() : null;
    }
    

提交回复
热议问题