Issue
I have a class Crop
that throws a NotSerializableException when it is passed through an intent to another Activity
. But if it is from an Activity
to a Fragment
(through Bundles
), there's no error and I can see the drawable object in the other side with no errors whatsoever.
How can it be serializable in one case but not in the other ?
public class Crop implements Serializable {
private String specieHarvest;
private String specieLocation;
private String specieName;
private Drawable img;
}
Solution
First, let's answer your question.
The reason of the behavior you are seeing is that
- Passing objects as extras to an
activity
, will always cause that object to be marshaled/un-marshaled by Android, it is thought of as some kind of IPC. - Passing objects as arguments to a
fragment
will not always cause your object to be marshaled.
Then when is your object taken apart and reconstructed by Android when sent to a fragment?
It will not be serialized/de-serialized unless the fragment is destroyed and recreated for some reason, otherwise, that object is kept in a map and the same object is returned to you when you call getArguments().
If you even change that object in the Fragment
, it will change the original one that was sent, because it is in fact the same reference. CRAZY, right? :)
If you take a look at Drawable
class, you will find that it is not Parcelable
or Serializable
, so don't pass it along in intents/arguments.
Instead, pass an int which can be the resource ID if the Drawable
object is in your resources, or you can pass a String
path if that is an image that is stored locally somewhere.
Also, passing int or string is much better, because Drawables
tend to be large is size, which might cause your app to crash due to size exceeded for an intent extras.
Here's an article where you can read about that as well.
Answered By - elmorabea
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.