Gal6111
Gal6111

Reputation: 53

Save custom arraylist to Shared Prefrences with gson

I am trying to save the state of my app to shared prefrences. The information that I want to save is an arraylist of custom objects where each object (PatientInfo) contains a few string and 2 more custom arraylist (SkinPhotoInfo, TreatmentsInfo). I was able to save and load an array list of custom objects, but I was'nt able to save the arraylist that has arraylists in it.

Anyone got an idea of what is the easiest way to do it? The object itself is allready parcable if it helps in any way.

P. S. When is the best time to save to shared prefrences - onPause or onDelete?

Thank you for your help!!

PatientInfo:

public class PatientInfo implements Parcelable {

String name;
String skinType;
String notes;
String image;
ArrayList<SkinPhotoInfo> skinPhotos;
ArrayList<TreatmentsInfo> treatments;
Boolean showDeleteButton;

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(name);
    dest.writeString(skinType);
    dest.writeString(notes);
    dest.writeValue(image);
    dest.writeValue(skinPhotos);
    dest.writeValue(treatments);
}

public static final Creator<PatientInfo> CREATOR = new Creator<PatientInfo>()
{
    @Override
    public PatientInfo createFromParcel(Parcel source) {
        PatientInfo ret = new PatientInfo();
        ret.name = source.readString();
        ret.skinType = source.readString();
        ret.notes = source.readString();
        ret.image = (String)source.readString();
        ret.skinPhotos = source.readArrayList(null);
        ret.treatments = source.readArrayList(null);

        return ret;
    }

    @Override
    public PatientInfo[] newArray(int size) {
        return new PatientInfo[size];
    }
};

public PatientInfo() {
    this.name = "";
    this.skinType = "";
    this.image = "";
    this.skinPhotos = new ArrayList<SkinPhotoInfo>();
    this.showDeleteButton = false;
    this.treatments = new ArrayList<TreatmentsInfo>();
}}

SkinPhotoInfo:

public class SkinPhotoInfo implements Parcelable {

String photoDate;
Boolean showDeleteButton;
Uri imageUri;

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(photoDate);
    dest.writeByte((byte)(showDeleteButton ? 1 : 0)); // If showDeleteButton == true, byte == 1
    dest.writeValue(imageUri);
}

public static final Creator<SkinPhotoInfo> CREATOR = new Creator<SkinPhotoInfo>()
{
    @Override
    public SkinPhotoInfo createFromParcel(Parcel source) {
        SkinPhotoInfo ret = new SkinPhotoInfo();
      ret.skinImageThumnail = (Bitmap)source.readValue(Bitmap.class.getClassLoader());
        ret.photoDate = source.readString();
        ret.showDeleteButton = source.readByte() != 1;
        ret.imageUri = (Uri) source.readValue(Uri.class.getClassLoader());
        return ret;
    }

    @Override
    public SkinPhotoInfo[] newArray(int size) {
        return new SkinPhotoInfo[size];
    }
};

    public SkinPhotoInfo(Uri imageUri, String photoDate) {
    this.imageUri = imageUri;
    this.photoDate = photoDate;
    showDeleteButton = false;
}}

TreatmentsInfo:

public class TreatmentsInfo implements Parcelable {
String treatmentDate;
String treatmentName;
String pattern = "MM-dd-yy";
Boolean showDeleteButton;

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(treatmentDate);
    dest.writeString(treatmentName);
    dest.writeString(pattern);
    dest.writeByte((byte)(showDeleteButton ? 1 : 0)); // If showDeleteButton == true, byte == 1
}

public static final Creator<TreatmentsInfo> CREATOR = new Creator<TreatmentsInfo>()
{
    @Override
    public TreatmentsInfo createFromParcel(Parcel source) {
        TreatmentsInfo ret = new TreatmentsInfo();
        ret.treatmentDate = source.readString();
        ret.treatmentName = source.readString();
        ret.pattern = source.readString();
        ret.showDeleteButton = source.readByte() != 1;
        return ret;
    }

    @Override
    public TreatmentsInfo[] newArray(int size) {
        return new TreatmentsInfo[size];
    }
};

public TreatmentsInfo(){
    this.treatmentDate = "";
    this.treatmentName = "";
    this.showDeleteButton = false;
    this.pattern = "";
}

public TreatmentsInfo(String treatmentDate, String treatmentName) {
    this.treatmentDate = treatmentDate;
    this.treatmentName = treatmentName;
    this.showDeleteButton = false;
}}

Upvotes: 1

Views: 118

Answers (5)

Black mamba
Black mamba

Reputation: 472

Convert response to gson and use it as list and thus simply convert list setvalue and use putArray() to that set

public class staticpref{
  private static SharedPreferences prefs;
   private static SharedPreferences.Editor editor;

 public static void putArray(String key, Set<String> arrayList){
    editor.putStringSet(key, arrayList);
    editor.commit();
}

public static Set getArray(String key,Set<String> defvalue){
    return prefs.getStringSet(key,defvalue);
}

}

or you can make static class for getting and array you have to convert gson to arraylist and like this

String strResponse = anyjsonResponse;
Modelclass model= new Gson().fromJson(strResponse, Modelclass .class);
List<String> datalist= model.anyvalue();
Putandgetarray.addArrayList(datalist);

static methods for achieving this

public class Putandgetarray{

public static void addArrayList(List<data> dataList){
    String strputdata = new Gson().toJson(dataList, new TypeToken<List<MutedChat>>() {}.getType());
    SharedPreferenceUtils.putString("key", strputdata);
}

public static List<data> getArrayList(){
    Type type = new TypeToken<List<data>>(){}.getType();
    String strreturndata=SharedPreferenceUtils.getString("key","");
    return  new Gson().fromJson(strreturndata, type);
}

}

Upvotes: 0

Rodrigo Fernandes
Rodrigo Fernandes

Reputation: 177

You can do something like:

String json = new Gson().toJson(YourObject);

To save in the Shared Preferences. To retrieve the json and transform it to YourObejct, just do:

String json = myPrefsObject.getString(TAG, "");    
return new Gson().fromJson(json, YourObject.class);

As for the PS question, the answer is onPause. Let me know if you need something else

Upvotes: 1

Bali
Bali

Reputation: 759

GSON provides method to convert objects to string and vice versa.

Use toJson() to convert object to string

PatientInfo patientInfo = new PatientInfo();
Gson gson = new Gson();   
String objectAsString = gson.toJson(patientInfo);   

Use fromJson() to convert string to object

Gson gson = new Gson();
PatientInfo  patientinfo = gson.fromJson(data, PatientInfo.class);
//data is object that that you saved in shared preference after converting to string

Upvotes: 0

kabayaba
kabayaba

Reputation: 204

Use Gson library and save the arraylist as string. Snippet below is save as file but you can use it in sharedpreference as well:

public static void saveGroupChatFile(File file, List<GCRoom> list) throws IOException {
    String data = new Gson().toJson(list);
    FileOutputStream fout = new FileOutputStream(file, false);
    OutputStreamWriter osw = new OutputStreamWriter(fout);
    osw.write(data);
    osw.close();
}

public static List<GCRoom> readGroupChatFile(File file) throws IOException {
    Type listType = new TypeToken<List<GCRoom>>() {
    }.getType();
    JsonReader reader = new JsonReader(new FileReader(file));

    return new Gson().fromJson(reader, listType);
}

As for the library:

implementation 'com.google.code.gson:gson:2.8.5'

Upvotes: 1

Neha Rathore
Neha Rathore

Reputation: 427

In sharedPreferece you can put only putStringSet(String key, @Nullable Set values); in sharedpreference

Upvotes: -1

Related Questions