Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize null value when using Parcelable interface

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.

@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());     }  } 

Thanks!

like image 342
igor.beslic Avatar asked May 05 '11 23:05

igor.beslic


People also ask

Which is better Parcelable or serializable?

Parcel able is faster than serializable. Parcel able is going to convert object to byte stream and pass the data between two activities. Writing parcel able code is little bit complex compare to serialization. It doesn't create more temp objects while passing the data between two activities.

What is a primary purpose of the Parcelable interface?

The Parcelable interface adds methods to all classes you want to be able to transfer between activities. These methods are how parcelable deconstructs the object in one activity and reconstructs it in another.

How do you implement Parcelable?

Create Parcelable class without plugin in Android Studioimplements Parcelable in your class and then put cursor on "implements Parcelable" and hit Alt+Enter and select Add Parcelable implementation (see image). that's it.

What is Parcelable data?

A Parcelable is the Android implementation of the Java Serializable. It assumes a certain structure and way of processing it. This way a Parcelable can be processed relatively fast, compared to the standard Java serialization.


Video Answer


2 Answers

You can use Parcel.writeValue for marshalling generic object with null value.

like image 196
artch Avatar answered Sep 24 '22 00:09

artch


I'm using a Parcelable class that has Integer and Boolean fields as well, and those fields can be null.

I had trouble using the generic Parcel.writeValue method, particularly when I was trying to read it back out via Parcel.readValue. I kept getting a runtime exception that said it couldn't figure out the type of the parceled object.

Ultimately, I was able to solve the problem by using Parcel.writeSerializable and Parcel.readSerializable with a type cast, as both Integer and Boolean implement the Serializable interface. The read and write methods handle null values for you.

like image 31
Justin Hong Avatar answered Sep 27 '22 00:09

Justin Hong