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?
当前回答
为什么不把数组列表放在应用程序类上呢?它只有在应用被杀死时才会被销毁,所以,只要应用可用,它就会一直存在。
其他回答
使用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()
}
}
从SharedPreference中保存和检索ArrayList
public static void addToPreference(String id,Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.MyPreference, Context.MODE_PRIVATE);
ArrayList<String> list = getListFromPreference(context);
if (!list.contains(id)) {
list.add(id);
SharedPreferences.Editor edit = sharedPreferences.edit();
Set<String> set = new HashSet<>();
set.addAll(list);
edit.putStringSet(Constant.LIST, set);
edit.commit();
}
}
public static ArrayList<String> getListFromPreference(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.MyPreference, Context.MODE_PRIVATE);
Set<String> set = sharedPreferences.getStringSet(Constant.LIST, null);
ArrayList<String> list = new ArrayList<>();
if (set != null) {
list = new ArrayList<>(set);
}
return list;
}
public void saveUserName(Context con,String username)
{
try
{
usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
usernameEditor = usernameSharedPreferences.edit();
usernameEditor.putInt(PREFS_KEY_SIZE,(USERNAME.size()+1));
int size=USERNAME.size();//USERNAME is arrayList
usernameEditor.putString(PREFS_KEY_USERNAME+size,username);
usernameEditor.commit();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void loadUserName(Context con)
{
try
{
usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
size=usernameSharedPreferences.getInt(PREFS_KEY_SIZE,size);
USERNAME.clear();
for(int i=0;i<size;i++)
{
String username1="";
username1=usernameSharedPreferences.getString(PREFS_KEY_USERNAME+i,username1);
USERNAME.add(username1);
}
usernameArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, USERNAME);
username.setAdapter(usernameArrayAdapter);
username.setThreshold(0);
}
catch(Exception e)
{
e.printStackTrace();
}
}
这就是你的完美解决方案。试一试,
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);
}
您还可以将数组列表转换为String并优先保存
private String convertToString(ArrayList<String> list) {
StringBuilder sb = new StringBuilder();
String delim = "";
for (String s : list)
{
sb.append(delim);
sb.append(s);;
delim = ",";
}
return sb.toString();
}
private ArrayList<String> convertToArray(String string) {
ArrayList<String> list = new ArrayList<String>(Arrays.asList(string.split(",")));
return list;
}
您可以使用convertToString方法将数组列表转换为字符串后保存它,并使用convertToArray方法检索字符串并将其转换为数组
在API 11之后,你可以直接保存设置到SharedPreferences !!:)
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在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)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?