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?
当前回答
我使用相同的方式保存和检索字符串,但这里我使用HashSet作为数组列表的中介
使用HashSet保存arrayList到SharedPreferences:
1-我们创建SharedPreferences变量(在数组发生变化的地方)
2 -我们将数组列表转换为HashSet
3 -然后放入stringSet并应用
4 -你在HashSet中获取stringset并重新创建ArrayList来设置HashSet。
public class MainActivity extends AppCompatActivity {
ArrayList<String> arrayList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences prefs = this.getSharedPreferences("com.example.nec.myapplication", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(arrayList);
prefs.edit().putStringSet("names", set).apply();
set = (HashSet<String>) prefs.getStringSet("names", null);
arrayList = new ArrayList(set);
Log.i("array list", arrayList.toString());
}
}
其他回答
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();
}
}
//Set the values
intent.putParcelableArrayListExtra("key",collection);
//Retrieve the values
ArrayList<OnlineMember> onlineMembers = data.getParcelableArrayListExtra("key");
使用这个自定义类:
public class SharedPreferencesUtil {
public static void pushStringList(SharedPreferences sharedPref,
List<String> list, String uniqueListName) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(uniqueListName + "_size", list.size());
for (int i = 0; i < list.size(); i++) {
editor.remove(uniqueListName + i);
editor.putString(uniqueListName + i, list.get(i));
}
editor.apply();
}
public static List<String> pullStringList(SharedPreferences sharedPref,
String uniqueListName) {
List<String> result = new ArrayList<>();
int size = sharedPref.getInt(uniqueListName + "_size", 0);
for (int i = 0; i < size; i++) {
result.add(sharedPref.getString(uniqueListName + i, null));
}
return result;
}
}
使用方法:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferencesUtil.pushStringList(sharedPref, list, getString(R.string.list_name));
List<String> list = SharedPreferencesUtil.pullStringList(sharedPref, getString(R.string.list_name));
你可以使用Gson库保存字符串和自定义数组列表。
首先你需要创建一个函数来保存数组列表到SharedPreferences。
public void saveListInLocal(ArrayList<String> list, String key) {
SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply(); // This line is IMPORTANT !!!
}
你需要创建一个函数来从SharedPreferences获取数组列表。
public ArrayList<String> getListFromLocal(String key)
{
SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
如何调用保存和检索数组列表函数。
ArrayList<String> listSave=new ArrayList<>();
listSave.add("test1"));
listSave.add("test2"));
saveListInLocal(listSave,"key");
Log.e("saveArrayList:","Save ArrayList success");
ArrayList<String> listGet=new ArrayList<>();
listGet=getListFromLocal("key");
Log.e("getArrayList:","Get ArrayList size"+listGet.size());
不要忘记在你的应用级别build.gradle中添加gson库。
实现“com.google.code.gson: gson: 2.8.2”
使用Kotlin,对于简单的数组和列表,你可以这样做:
class MyPrefs(context: Context) {
val prefs = context.getSharedPreferences("x.y.z.PREFS_FILENAME", 0)
var listOfFloats: List<Float>
get() = prefs.getString("listOfFloats", "").split(",").map { it.toFloat() }
set(value) = prefs.edit().putString("listOfFloats", value.joinToString(",")).apply()
}
然后轻松访问首选项:
MyPrefs(context).listOfFloats = ....
val list = MyPrefs(context).listOfFloats
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在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)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?