J'essaie d'enregistrer l'état de mon application dans les préférences partagées. Les informations que je souhaite enregistrer sont une arraylist d'objets personnalisés où chaque objet (PatientInfo) contient quelques chaînes et 2 autres arraylist personnalisés (SkinPhotoInfo, TreatmentsInfo). J'ai pu enregistrer et charger une liste de tableaux d'objets personnalisés, mais je n'ai pas pu enregistrer l'arraylist qui contient des arraylists.
Quelqu'un a-t-il une idée de la manière la plus simple de le faire? L'objet lui-même est déjà parcable s'il aide de quelque manière que ce soit.
P. S. Quel est le meilleur moment pour enregistrer dans les préférences partagées - onPause ou onDelete?
Merci pour votre aide !!
Info Patient:
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 Réponses :
Dans sharedPreferece, vous ne pouvez mettre que putStringSet (String key, @Nullable Set values); dans les préférences partagées
Vous pouvez faire quelque chose comme:
String json = myPrefsObject.getString(TAG, ""); return new Gson().fromJson(json, YourObject.class);
Pour enregistrer dans les préférences partagées. Pour récupérer le json et le transformer en YourObejct, faites simplement:
String json = new Gson().toJson(YourObject);
Quant à la question PS, la réponse est onPause. Faites-moi savoir si vous avez besoin d'autre chose
Utilisez la bibliothèque Gson et enregistrez l'arraylist sous forme de chaîne. L'extrait ci-dessous est enregistré en tant que fichier, mais vous pouvez également l'utiliser dans les préférences partagées:
implementation 'com.google.code.gson:gson:2.8.5'
Quant à la bibliothèque:
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); }
GSON fournit une méthode pour convertir des objets en chaîne et vice versa.
Utilisez toJson ()
pour convertir l'objet en chaîne
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
fromJson ()
pour convertir la chaîne en objet
PatientInfo patientInfo = new PatientInfo(); Gson gson = new Gson(); String objectAsString = gson.toJson(patientInfo);
Convertissez la réponse en gson et utilisez-la comme liste et convertissez simplement la liste setvalue et utilisez putArray () en cet ensemble
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); }
}
ou vous pouvez créer une classe statique pour obtenir et un tableau, vous devez convertir gson en arraylist et comme ceciString strResponse = anyjsonResponse; Modelclass model= new Gson().fromJson(strResponse, Modelclass .class); List<String> datalist= model.anyvalue(); Putandgetarray.addArrayList(datalist);
méthodes statiques pour atteindre cet objectif
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); }
}