使用gson将自定义数组列表保存到Shared Prefrences

时间:2019-09-06 08:34:44

标签: java android gson

我正在尝试将我的应用程序状态保存到共享偏好设置中。我要保存的信息是自定义对象的数组列表,其中每个对象(PatientInfo)包含一些字符串和两个以上的自定义数组列表(SkinPhotoInfo,TreatmentsInfo)。我能够保存和加载自定义对象的数组列表,但无法保存其中包含数组列表的数组列表。

任何人都知道最简单的方法是什么?如果对象本身有任何帮助,它本身就已经可以解析。

P。 S.什么时候是保存到共享偏好的最佳时间-onPause或onDelete?

谢谢您的帮助!

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;
}}

5 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

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

保存在共享首选项中。 要检索json并将其转换为YourObejct,只需执行以下操作:

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

关于PS问题,答案为onPause。 让我知道您是否还需要其他东西

答案 1 :(得分:1)

使用Gson库并将arraylist保存为字符串。 下面的代码段另存为文件,但您也可以在sharedpreference中使用它:

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);
}

关于图书馆:

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

答案 2 :(得分:0)

GSON提供了将对象转换为字符串,反之亦然的方法。

使用toJson()将对象转换为字符串

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

使用fromJson()将字符串转换为对象

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

答案 3 :(得分:0)

将响应转换为gson并将其用作列表,因此只需转换列表setvalue并使用putArray()对该列表进行设置

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);
}

}

或者您可以使静态类用于获取和数组,您必须将gson转换为arraylist并以此方式

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

实现这一目标的静态方法

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);
}

}

答案 4 :(得分:-1)

在sharedPreferece中,您只能放置putStringSet(String key,@Nullable Set values);共享首选项