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?
当前回答
该方法用于存储/保存数组列表:-
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;
}
其他回答
使用Kotlin和GSON:
fun <T> SharedPreferences.writeList(gson: Gson, key: String, data: List<T>) {
val json = gson.toJson(data)
edit { putString(key, json) }
}
inline fun <reified T> SharedPreferences.readList(gson: Gson, key: String): List<T> {
val json = getString(key, "[]") ?: "[]"
val type = object : TypeToken<List<T>>() {}.type
return try {
gson.fromJson(json, type)
} catch(e: JsonSyntaxException) {
emptyList()
}
}
这就是你的完美解决方案。试一试,
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(); // This line is IMPORTANT !!!
}
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);
}
在SharedPreferences中保存数组:
public static boolean saveArray()
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor mEdit1 = sp.edit();
/* sKey is an array */
mEdit1.putInt("Status_size", sKey.size());
for(int i=0;i<sKey.size();i++)
{
mEdit1.remove("Status_" + i);
mEdit1.putString("Status_" + i, sKey.get(i));
}
return mEdit1.commit();
}
从SharedPreferences加载数组数据
public static void loadArray(Context mContext)
{
SharedPreferences mSharedPreference1 = PreferenceManager.getDefaultSharedPreferences(mContext);
sKey.clear();
int size = mSharedPreference1.getInt("Status_size", 0);
for(int i=0;i<size;i++)
{
sKey.add(mSharedPreference1.getString("Status_" + i, null));
}
}
您可以将其转换为Map Object来存储它,然后在检索SharedPreferences时将值更改回ArrayList。
Android sharedpreferences允许您将基本类型(Boolean, Float, Int, Long, String和StringSet,自API11以来可用)作为xml文件保存在内存中。
任何解决方案的关键思想都是将数据转换为这些基本类型之一。
我个人喜欢将my list转换为json格式,然后将其保存为SharedPreferences值中的字符串。
为了使用我的解决方案,你必须添加谷歌gsonlib。
在gradle中只需添加以下依赖项(请使用谷歌的最新版本):
compile 'com.google.code.gson:gson:2.6.2'
保存数据(HttpParam是你的对象):
List<HttpParam> httpParamList = "**get your list**"
String httpParamJSONList = new Gson().toJson(httpParamList);
SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(**"your_prefes_key"**, httpParamJSONList);
editor.apply();
检索数据(HttpParam是你的对象):
SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
String httpParamJSONList = prefs.getString(**"your_prefes_key"**, "");
List<HttpParam> httpParamList =
new Gson().fromJson(httpParamJSONList, new TypeToken<List<HttpParam>>() {
}.getType());
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在Android中将字符串转换为Uri
- 如何在NestedScrollView内使用RecyclerView ?
- 移动到另一个EditText时,软键盘下一步点击Android
- Android应用中的GridView VS GridLayout
- Activity和FragmentActivity的区别
- 右对齐文本在android TextView
- 权限拒绝:start前台需要android.permission.FOREGROUND_SERVICE
- 如何更改android操作栏的标题和图标
- Android Split字符串
- 让一个链接在安卓浏览器启动我的应用程序?
- 如何在Android工作室的外部库中添加一个jar ?
- GridLayout(不是GridView)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?