Ernesto Delgado
Ernesto Delgado

Reputation: 299

how to serialize HashSet

i'm building an android app and i want to add a history function. I heard that i can serialize a list to be able to save and retrieve data instead of using a Database, i have no idea how it works so i come here and ask for advice, is there somewhere i could get started with this. Some good links could be useful.

Thanks

Upvotes: 2

Views: 7354

Answers (2)

blindstuff
blindstuff

Reputation: 18348

You should not use serializable, android implements parcelables in a much much more effective way. The catch is you have to define how parcel the object yourself, but it really isnt that hard.

Simple example:

public class MyParcelable implements Parcelable {
     private int mData;

     public int describeContents() {
         return 0;
     }

     public void writeToParcel(Parcel out, int flags) {
         out.writeInt(mData);
     }

     public static final Parcelable.Creator<MyParcelable> CREATOR
             = new Parcelable.Creator<MyParcelable>() {
         public MyParcelable createFromParcel(Parcel in) {
             return new MyParcelable(in);
         }

         public MyParcelable[] newArray(int size) {
             return new MyParcelable[size];
         }
     };

     private MyParcelable(Parcel in) {
         mData = in.readInt();
     }
 }

If you want to save a Hashset, you just need to make sure that the objects inside the Hash are also parcelable.

If you feel this is too much trouble, the answer previously posted by Nailuj is right.

Upvotes: 1

Julian
Julian

Reputation: 20324

HashSet implements Serializable. So as long as all the objects you put inside your hash set also implements Serializable (and all objects inside them again etc.), you can serialize it as any other normal serializable java object.

Upvotes: 18

Related Questions