Java 如何将 List<Object> 保存到 SharedPreferences?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28107647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to save List<Object> to SharedPreferences?
提问by kakajan
I have a list of products, which i retrieve from webservice, when app is opened for first time, app gets product list from webservice. I want to save this list to shared preferences.
我有一个产品列表,我从网络服务中检索,当应用程序第一次打开时,应用程序从网络服务中获取产品列表。我想将此列表保存到共享首选项。
List<Product> medicineList = new ArrayList<Product>();
where Product class is:
其中产品类是:
public class Product {
public final String productName;
public final String price;
public final String content;
public final String imageUrl;
public Product(String productName, String price, String content, String imageUrl) {
this.productName = productName;
this.price = price;
this.content = content;
this.imageUrl = imageUrl;
}
}
how i can save this List not requesting from webservice each time?
我如何保存这个列表而不是每次都从 webservice 请求?
采纳答案by ar-g
It only possible to use primitive types because preference keep in memory. But what you can use is serialize your types with Gson into json and put string into preferences:
只能使用原始类型,因为偏好保留在内存中。但是您可以使用的是将您的类型与 Gson 序列化为 json 并将字符串放入首选项中:
private static SharedPreferences sharedPreferences = context.getSharedPreferences(STORE_FILE_NAME, Context.MODE_PRIVATE);
private static SharedPreferences.Editor editor = sharedPreferences.edit();
public <T> void setList(String key, List<T> list) {
Gson gson = new Gson();
String json = gson.toJson(list);
set(key, json);
}
public static void set(String key, String value) {
editor.putString(key, value);
editor.commit();
}
回答by MDMalik
You currently have two options
a) Use SharedPreferences
b) Use SQLite and save values in that.
您目前有两个选项
a) 使用 SharedPreferences
b) 使用 SQLite 并在其中保存值。
How to perform
a) SharedPreferences
First store your List as a Set, and then convert it back to a List when you read from SharedPreferences.
如何执行
a) SharedPreferences
首先将您的 List 存储为 Set,然后在您从 SharedPreferences 读取时将其转换回 List。
Listtasks = new ArrayList<String>();
Set<String> tasksSet = new HashSet<String>(Listtasks);
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putStringSet("tasks_set", tasksSet)
.commit();
Then when you read it:
然后当你阅读它时:
Set<String> tasksSet = PreferenceManager.getDefaultSharedPreferences(context)
.getStringSet("tasks_set", new HashSet<String>());
List<String> tasksList = new ArrayList<String>(tasksSet);
b) SQLite A good tutorial: http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
b) SQLite 一个很好的教程:http: //www.androidhive.info/2011/11/android-sqlite-database-tutorial/
回答by Dario
In SharedPreferences you can store only primitives.
在 SharedPreferences 中,您只能存储原语。
As one possible approach is that you can use GSON and store values into preferences in JSON.
一种可能的方法是您可以使用 GSON 并将值存储到 JSON 中的首选项中。
Gson gson = new Gson();
String json = gson.toJson(medicineList);
yourPrefereces.putString("listOfProducts", json);
yourPrefereces.commit();
回答by waqaslam
You may do it using Gson
as below:
您可以使用Gson
以下方法进行操作:
- Download
List<Product>
from webservice - Convert the
List
into JsonString
usingnew Gson().toJson(medicineList, new TypeToken<List<Product>>(){}.getType())
- Save the converted string into
SharePreferences
as you do normally
List<Product>
从网络服务下载- 转换
List
成Json的String
使用new Gson().toJson(medicineList, new TypeToken<List<Product>>(){}.getType())
SharePreferences
像往常一样将转换后的字符串保存到
In order to reconstruct your List
, you need to revert the process using fromJsonmethod available in Gson
.
为了重建你的List
,你需要恢复使用过程fromJson中可用的方法Gson
。
回答by rafaelasguerra
You can use GSON to convert Object -> JSON(.toJSON) and JSON -> Object(.fromJSON).
您可以使用 GSON 来转换 Object -> JSON(.toJSON) 和 JSON -> Object(.fromJSON)。
Define your Tags with you want (for example):
private static final String PREFS_TAG = "SharedPrefs"; private static final String PRODUCT_TAG = "MyProduct";
Get your sharedPreference to these tag's
private List<Product> getDataFromSharedPreferences(){ Gson gson = new Gson(); List<Product> productFromShared = new ArrayList<>(); SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PREFS_TAG, Context.MODE_PRIVATE); String jsonPreferences = sharedPref.getString(PRODUCT_TAG, ""); Type type = new TypeToken<List<Product>>() {}.getType(); productFromShared = gson.fromJson(jsonPreferences, type); return preferences; }
Set your sharedPreferences
private void setDataFromSharedPreferences(Product curProduct){ Gson gson = new Gson(); String jsonCurProduct = gson.toJson(curProduct); SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PREFS_TAG, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(PRODUCT_TAG, jsonCurProduct); editor.commit(); }
If you want to save an array of Products, do this:
private void addInJSONArray(Product productToAdd){ Gson gson = new Gson(); SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PREFS_TAG, Context.MODE_PRIVATE); String jsonSaved = sharedPref.getString(PRODUCT_TAG, ""); String jsonNewproductToAdd = gson.toJson(productToAdd); JSONArray jsonArrayProduct= new JSONArray(); try { if(jsonSaved.length()!=0){ jsonArrayProduct = new JSONArray(jsonSaved); } jsonArrayProduct.put(new JSONObject(jsonNewproductToAdd)); } catch (JSONException e) { e.printStackTrace(); } //SAVE NEW ARRAY SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(PRODUCT_TAG, jsonArrayProduct); editor.commit(); }
用你想要的方式定义你的标签(例如):
private static final String PREFS_TAG = "SharedPrefs"; private static final String PRODUCT_TAG = "MyProduct";
获取您对这些标签的 sharedPreference
private List<Product> getDataFromSharedPreferences(){ Gson gson = new Gson(); List<Product> productFromShared = new ArrayList<>(); SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PREFS_TAG, Context.MODE_PRIVATE); String jsonPreferences = sharedPref.getString(PRODUCT_TAG, ""); Type type = new TypeToken<List<Product>>() {}.getType(); productFromShared = gson.fromJson(jsonPreferences, type); return preferences; }
设置您的共享首选项
private void setDataFromSharedPreferences(Product curProduct){ Gson gson = new Gson(); String jsonCurProduct = gson.toJson(curProduct); SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PREFS_TAG, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(PRODUCT_TAG, jsonCurProduct); editor.commit(); }
如果要保存一系列产品,请执行以下操作:
private void addInJSONArray(Product productToAdd){ Gson gson = new Gson(); SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PREFS_TAG, Context.MODE_PRIVATE); String jsonSaved = sharedPref.getString(PRODUCT_TAG, ""); String jsonNewproductToAdd = gson.toJson(productToAdd); JSONArray jsonArrayProduct= new JSONArray(); try { if(jsonSaved.length()!=0){ jsonArrayProduct = new JSONArray(jsonSaved); } jsonArrayProduct.put(new JSONObject(jsonNewproductToAdd)); } catch (JSONException e) { e.printStackTrace(); } //SAVE NEW ARRAY SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(PRODUCT_TAG, jsonArrayProduct); editor.commit(); }
回答by Walter Palladino
All the answer related to JSON are Ok but remember Java allows you to serialize any object if you implement the java.io.Serializable interface. This way you can save it to preferences as a serialized object too. Here is an example for storing as Preferences: https://gist.github.com/walterpalladino/4f5509cbc8fc3ecf1497f05e37675111I hope this could help you as an option.
所有与 JSON 相关的答案都可以,但请记住,如果您实现了 java.io.Serializable 接口,Java 允许您序列化任何对象。通过这种方式,您也可以将其作为序列化对象保存到首选项中。以下是存储为首选项的示例:https: //gist.github.com/walterpalladino/4f5509cbc8fc3ecf1497f05e37675111我希望这可以帮助您作为一种选择。
回答by taran mahal
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
For save
为了保存
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
For get
忘记
Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);
回答by Shylendra Madda
As said in accepted answer we can save list of objects like:
正如在接受的答案中所说,我们可以保存对象列表,例如:
public <T> void setList(String key, List<T> list) {
Gson gson = new Gson();
String json = gson.toJson(list);
set(key, json);
}
public void set(String key, String value) {
if (setSharedPreferences != null) {
SharedPreferences.Editor prefsEditor = setSharedPreferences.edit();
prefsEditor.putString(key, value);
prefsEditor.commit();
}
}
Get it by using:
通过使用获取它:
public List<Company> getCompaniesList(String key) {
if (setSharedPreferences != null) {
Gson gson = new Gson();
List<Company> companyList;
String string = setSharedPreferences.getString(key, null);
Type type = new TypeToken<List<Company>>() {
}.getType();
companyList = gson.fromJson(string, type);
return companyList;
}
return null;
}
回答by rahimpourDeveloper
The best solution for me and I think you :
对我来说最好的解决方案,我认为你:
private static SharedPreferences sharedPreferences = context.getSharedPreferences(STORE_FILE_NAME, Context.MODE_PRIVATE);
private SharedPreferences.Editor editor = sharedPreferences.edit();
List<your object> list = new ArrayList<>();
For save:
为了保存:
editor.edit().putString("your key name", new Gson().toJson(list)).apply();
For get:
忘记:
list = new Gson().fromJson(sharedPreferences.getString("your key name", null), new TypeToken<List<your object class name>>(){}.getType());
enjoy it!
好好享受!