Home Ask Login Register

Developers Planet

Your answer is one click away!

Adam Varhegyi February 2016

Is it safe to serialize a class instance with a resource reference attribute?

I would like to serialize an object like:

   class Dog implements Serializable{

       public String name;
       public int iconDrawable;

the iconDrawable is an int pointing to a drawable resource from R.java.

So i can just make a Dog like this:

Dog dog = new Dog();
dog.name= "Barky";
dog.iconDrawable = R.drawable.dog_icon; //portrait of a dog instance

My question is:

Is it safe to serialize this object? Is the iconDrawable is a final number and do I get the same drawable always when i de-serialize? Or the reference could change on app startup or app termination?

Or should I store the name of the drawable in a String attribute field and use getIdentifier? (Little more complicated but works for sure)


George Mulligan February 2016

R.java is generated for you at build time. It will change if you modify (add, remove, etc) resources or possibly if a new version of the Android Build Tools is used to build the project.

That being said it would be safe to serialize/deserialize the resource id if you were only using it to transport the object to another activity/fragment or something similar during runtime.

However, if you are serializing it for persistence that would not be safe as those ids can change as mentioned between application builds. In that case it would be best to use getIdentifier.

Post Status

Asked in February 2016
Viewed 1,256 times
Voted 7
Answered 1 times


Leave an answer

Quote of the day: live life