gpt4 book ai didi

java - Android:在 SharedPreferences 中存储 ArrayList

转载 作者:行者123 更新时间:2023-11-30 11:10:40 25 4
gpt4 key购买 nike

我需要在我的 SharedPreferences 中存储一个类型为“Comment”的 ArrayList。这是我的模型类:

public class Comment {

public String getPID() {
return PID;
}
public void setPID(String pID) {
PID = pID;
}
public String PID;
public String Comment;
public String Commenter;
public String Date;

public String getComment() {
return Comment;
}
public void setComment(String comment) {
Comment = comment;
}
public String getCommenter() {
return Commenter;
}
public void setCommenter(String commenter) {
Commenter = commenter;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
}

因此我的 ArrayList 包含 2 个需要存储在 SharedPreferences 中的 Comments。我试过 HashSet 但它需要字符串值:

ArrayList<Comment_FB> fb = getFeedback(); //my Comments List

SharedPreferences pref = getApplicationContext().getSharedPreferences("CurrentProduct", 0);
Editor editor = pref.edit();
Set<String> set = new HashSet<String>();
set.addAll(fb);
editor.putStringSet("key", set);
editor.commit();

伙计们,我该如何完成这项工作? :)

最佳答案

我认为您需要将其存储为文件。

public static boolean save(String key, Serializable obj) {
try {
FileOutputStream outStream = new FileOutputStream(instance.getCacheDir() + "/" + key);
ObjectOutputStream objOutStream;
objOutStream = new ObjectOutputStream(outStream);
objOutStream.writeObject(obj);
} catch (Exception e) {
e.printStackTrace();
return false;
}

return true;
}


public static Object getObject(String key) {
Object obj = null;
if (!new File(instance.getCacheDir() + "/" + key).exists())
return obj;
FileInputStream inputStream;
try {
inputStream = new FileInputStream(instance.getCacheDir() + "/" + key);
ObjectInputStream objInputStream = new ObjectInputStream(inputStream);
obj = objInputStream.readObject();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}

您的“评论”类应该实现Serializable

关于java - Android:在 SharedPreferences 中存储 ArrayList<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27631280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com