I have a custom model class which implements Parcelable. It contains 3 strings i.e. String id_url,position,type . The complete class is :
public class Facebook_Images_Data implements Parcelable {
String id_url;
String position;
String type;
public Facebook_Images_Data(
String id_url, String position, String type) {
this.id_url = id_url;
this.position = position;
this.type = type;
}
public String getId_url() {
return id_url;
}
public void setId_url(String id_url) {
this.id_url = id_url;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
protected Facebook_Images_Data(Parcel in) {
id_url = in.readString();
position = in.readString();
type = in.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id_url);
dest.writeString(position);
dest.writeString(type);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<Facebook_Images_Data> CREATOR = new Parcelable.Creator<Facebook_Images_Data>() {
@Override
public Facebook_Images_Data createFromParcel(Parcel in) {
return new Facebook_Images_Data(in);
}
@Override
public Facebook_Images_Data[] newArray(int size) {
return new Facebook_Images_Data[size];
}
};
}
After creating the ArrayList
of this Model, I need to pass some values to the arraylist. Upto here, its working fine. But how I store this into sharedpreferences and fetch it afterwards. (Main motive is to get respective values properly)
Use gson library for this.
ArrayList<Facebook_Images_Data> listData = new ArrayList<Facebook_Images_Data>();
Gson gson = new Gson();
String stringValue = gson.toJson(listData);
prefsEditor.putString("KEY",stringValue);
For Fetching :
Gson gson = new Gson();
ArrayList<Facebook_Images_Data> restoredData = gson.fromJson(sharedPreference.getString("KEY"), new TypeToken<ArrayList<Facebook_Images_Data>>() {}.getType());