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!
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.
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.
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.
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.
You can use Parcel.writeValue for marshalling generic object with null value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With