development

Parcelable 인터페이스를 사용할 때 null 값을 직렬화하는 방법

big-blog 2020. 12. 3. 08:05
반응형

Parcelable 인터페이스를 사용할 때 null 값을 직렬화하는 방법


내 코드 예제와 관련하여 Locable의 변수가 null 인 경우 어떻게해야합니까? 예를 들어 l.getZoom ()이 null을 반환하면 NullPointerException이 발생합니다.

@Override
public void writeToParcel(Parcel parcel, int arg1) {
    parcel.writeInt(count);
    for(Locable l:locableArr){
        parcel.writeInt(l.getOriginId());
        parcel.writeInt(l.getLocableType());
        parcel.writeInt(l.getZoom());
        parcel.writeDouble(l.getLatituda());
        parcel.writeDouble(l.getLongituda());
        parcel.writeString(l.getTitle());
        parcel.writeString(l.getSnipet());
    }

}

감사!


Parcel.writeValuenull 값으로 일반 개체를 마샬링 하는 데 사용할 수 있습니다 .


필드도 있는 Parcelable클래스를 사용하고 있으며 해당 필드는 null 일 수 있습니다.IntegerBoolean

Parcel.writeValue특히 .NET을 통해 다시 읽으려고 할 때 일반적인 방법을 사용하는 데 문제가 Parcel.readValue있습니다. 구획 된 객체의 유형을 파악할 수 없다는 런타임 예외가 계속 발생했습니다.

궁극적으로, 나는 사용하여 문제를 해결할 수 있었다 Parcel.writeSerializable그리고 Parcel.readSerializable모두 같은 타입 캐스트 IntegerBooleanSerializable 인터페이스를 구현합니다. 읽기 및 쓰기 메서드는 null값을 처리 합니다.


이것은 문자열을 안전하게 작성하기 위해 고안 한 솔루션입니다.

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;
}

내가 본 대부분의 직렬화 코드는 값의 존재 / 부재를 나타 내기 위해 플래그를 사용하거나 값이없는 경우 카운트 필드가 0으로 설정되는 카운트 필드 (예 : 배열을 작성할 때)가 값 앞에옵니다. t는 전혀 존재하지 않습니다.

Android 핵심 클래스의 소스 코드를 살펴보면 다음과 같은 코드가 나타납니다 (Message 클래스에서).

    if (obj != null) {
        try {
            Parcelable p = (Parcelable)obj;
            dest.writeInt(1);
            dest.writeParcelable(p, flags);
        } catch (ClassCastException e) {
            throw new RuntimeException(
                "Can't marshal non-Parcelable objects across processes.");
        }
    } else {
        dest.writeInt(0);
    }

또는 (Intent 클래스에서) :

    if (mCategories != null) {
        out.writeInt(mCategories.size());
        for (String category : mCategories) {
            out.writeString(category);
        }
    } else {
        out.writeInt(0);
    }

My suggestion: In your code, if there is no functional difference between "zoom == null" and "zoom == 0", then I would just declare zoom as a primitive (int instead of Integer) OR initialize it to zero in the constructor and ensure that you never set it to null (then you can be guaranteed that it will never be null and you won't have to add special code to deal with that in your serialization/deserialization methods).

참고URL : https://stackoverflow.com/questions/5905105/how-to-serialize-null-value-when-using-parcelable-interface

반응형