I have an ArrayList with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves the activity and then wants to come back at a later time, however I don't need the array available after the application has been closed completely. I save a lot of other objects this way by using the SharedPreferences but I can't figure out how to save my entire array this way. Is this possible? Maybe SharedPreferences isn't the way to go about this? Is there a simpler method?
当前回答
/**
* Save and get ArrayList in SharedPreference
*/
JAVA:
public void saveArrayList(ArrayList<String> list, String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply();
}
public ArrayList<String> getArrayList(String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
科特林
fun saveArrayList(list: java.util.ArrayList<String?>?, key: String?) {
val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
val editor: Editor = prefs.edit()
val gson = Gson()
val json: String = gson.toJson(list)
editor.putString(key, json)
editor.apply()
}
fun getArrayList(key: String?): java.util.ArrayList<String?>? {
val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
val gson = Gson()
val json: String = prefs.getString(key, null)
val type: Type = object : TypeToken<java.util.ArrayList<String?>?>() {}.getType()
return gson.fromJson(json, type)
}
其他回答
您可以将其转换为Map Object来存储它,然后在检索SharedPreferences时将值更改回ArrayList。
该方法用于存储/保存数组列表:-
public static void saveSharedPreferencesLogList(Context context, List<String> collageList) {
SharedPreferences mPrefs = context.getSharedPreferences("PhotoCollage", context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(collageList);
prefsEditor.putString("myJson", json);
prefsEditor.commit();
}
该方法用于检索数组列表:-
public static List<String> loadSharedPreferencesLogList(Context context) {
List<String> savedCollage = new ArrayList<String>();
SharedPreferences mPrefs = context.getSharedPreferences("PhotoCollage", context.MODE_PRIVATE);
Gson gson = new Gson();
String json = mPrefs.getString("myJson", "");
if (json.isEmpty()) {
savedCollage = new ArrayList<String>();
} else {
Type type = new TypeToken<List<String>>() {
}.getType();
savedCollage = gson.fromJson(json, type);
}
return savedCollage;
}
对于String, int, boolean,最好的选择是sharedPreferences。
如果你想存储数组列表或任何复杂的数据。最好的选择是Paper library。
添加依赖关系
implementation 'io.paperdb:paperdb:2.6'
初始化文件
应该在Application.onCreate()中初始化一次:
Paper.init(context);
Save
List<Person> contacts = ...
Paper.book().write("contacts", contacts);
加载数据
如果对象在存储中不存在,请使用默认值。
List<Person> contacts = Paper.book().read("contacts", new ArrayList<>());
给你。
https://github.com/pilgr/Paper
我已经阅读了上面所有的答案。这都是正确的,但我找到了一个更简单的解决方案如下:
Saving String List in shared-preference>> public static void setSharedPreferenceStringList(Context pContext, String pKey, List<String> pData) { SharedPreferences.Editor editor = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).edit(); editor.putInt(pKey + "size", pData.size()); editor.commit(); for (int i = 0; i < pData.size(); i++) { SharedPreferences.Editor editor1 = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).edit(); editor1.putString(pKey + i, (pData.get(i))); editor1.commit(); } } and for getting String List from Shared-preference>> public static List<String> getSharedPreferenceStringList(Context pContext, String pKey) { int size = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).getInt(pKey + "size", 0); List<String> list = new ArrayList<>(); for (int i = 0; i < size; i++) { list.add(pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).getString(pKey + i, "")); } return list; }
这里的常数。APP_PREFS是要打开的文件的名称;不能包含路径分隔符。
正如@nirav所说,最好的解决方案是使用Gson实用工具类将其作为json文本存储在sharedpreferences中。下面是示例代码:
//Retrieve the values
Gson gson = new Gson();
String jsonText = Prefs.getString("key", null);
String[] text = gson.fromJson(jsonText, String[].class); //EDIT: gso to gson
//Set the values
Gson gson = new Gson();
List<String> textList = new ArrayList<String>(data);
String jsonText = gson.toJson(textList);
prefsEditor.putString("key", jsonText);
prefsEditor.apply();
推荐文章
- 在Android中,对话框被取消或被取消有什么区别?
- 在ScrollView触摸处理中的HorizontalScrollView
- 何时在Android中使用RxJava,何时使用Android架构组件中的LiveData ?
- 如何在Android项目中使用ThreeTenABP
- 指定的子节点已经有一个父节点。你必须先在子对象的父对象上调用removeView() (Android)
- 我的Android设备没有出现在adb设备列表中
- 在没有安装apk的情况下获取Android .apk文件的VersionName或VersionCode
- Fragment onResume() & onPause()不会在backstack上被调用
- 如何设置基线对齐为假提高性能在线性布局?
- 如何获得当前屏幕方向?
- 如何在Android中渲染PDF文件
- 如何计算一个元素在列表中出现的次数
- 我如何解决错误“minCompileSdk(31)指定在一个依赖的AAR元数据”在本机Java或Kotlin?
- 如何改变TextInputLayout的浮动标签颜色
- Android工作室如何运行gradle同步手动?