Java 如何使用SharedReferences保存对象[]?

Java 如何使用SharedReferences保存对象[]?,java,android,Java,Android,我尝试了许多解决方案,但都不奏效。我不知道这些是错的,还是我做错了什么。我有MyClass[]array=newmyclass[]{objects声明…}我想用SharedReferences保存它。有人能给我完整的SaveIt(){}和LoadIt(){}代码来做这件事吗?不可能 您只能在SharedReferences中存储简单值 更新: 如果要使用横向库,请使用Gson库: dependencies { compile 'com.google.code.gson:gson:2.8.2' }

我尝试了许多解决方案,但都不奏效。我不知道这些是错的,还是我做错了什么。我有
MyClass[]array=newmyclass[]{objects声明…}我想用SharedReferences保存它。有人能给我完整的
SaveIt(){}
LoadIt(){}
代码来做这件事吗?

不可能

您只能在SharedReferences中存储简单值

更新:

如果要使用横向库,请使用Gson库:

dependencies {
compile 'com.google.code.gson:gson:2.8.2'
}
Gson gson = new Gson();
//Your json response object value store in json object
JSONObject jsonObject = response.getJSONObject();
//Convert json object to string
String json = gson.toJson(jsonObject);
//Store in the sharedpreference
getPrefs().setUserJson(json);
String json = getPrefs().getUserJson();
商店:

dependencies {
compile 'com.google.code.gson:gson:2.8.2'
}
Gson gson = new Gson();
//Your json response object value store in json object
JSONObject jsonObject = response.getJSONObject();
//Convert json object to string
String json = gson.toJson(jsonObject);
//Store in the sharedpreference
getPrefs().setUserJson(json);
String json = getPrefs().getUserJson();
检索:

dependencies {
compile 'com.google.code.gson:gson:2.8.2'
}
Gson gson = new Gson();
//Your json response object value store in json object
JSONObject jsonObject = response.getJSONObject();
//Convert json object to string
String json = gson.toJson(jsonObject);
//Store in the sharedpreference
getPrefs().setUserJson(json);
String json = getPrefs().getUserJson();

SharedReference
不是用来存储复杂对象、数组或列表的


因此,在您的情况下,我建议使用或SQLite作为本地数据库。您可以添加、删除或查询项目列表,这更灵活

我投票将此问题作为主题外的问题结束,因为堆栈溢出不是一种代码编写服务。请阅读本页以获取更多帮助。是否可以使用Gson?我想保存我自己做的类。但“response”和“getPrefs”的定义是什么?我添加了存储和检索代码,使用了它们,但我没有定义“response”和“getPrefs()”,当我尝试编译这个时,我得到错误“无法解析符号“response””好的,谢谢,如果我找不到使用SharedReference的方法,我将尝试以下领域:)