【问题标题】:Save custom arraylist to Shared Prefrences with gson使用 gson 将自定义数组列表保存到 Sharedpreferences
【发布时间】:2019-09-06 08:34:44
【问题描述】:

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

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

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

感谢您的帮助!!

患者信息:

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

皮肤照片信息:

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

治疗信息:

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

【问题讨论】:

    标签: java android gson


    【解决方案1】:

    使用 Gson 库并将数组列表保存为字符串。 下面的片段保存为文件,但您也可以在 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】:

      你可以这样做:

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

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

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

      至于PS问题,答案是onPause。 如果您还需要其他东西,请告诉我

      【讨论】:

        【解决方案3】:

        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
        

        【讨论】:

          【解决方案4】:

          将响应转换为 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);
          }
          

          }

          【讨论】:

            【解决方案5】:

            在 sharedPreferece 中你只能放 putStringSet(String key, @Nullable Set values);在共享偏好中

            【讨论】:

              猜你喜欢
              • 2018-09-16
              • 2022-09-27
              • 1970-01-01
              • 1970-01-01
              • 2017-12-28
              • 2020-11-28
              • 1970-01-01
              • 1970-01-01
              • 2015-08-19
              相关资源
              最近更新 更多