如何在Android的共享首选项中附加数据 [英] how to append data in Shared Preference in Android
问题描述
我尝试使用
SharedPreferences sharedPreferences = getSharedPreferences("myData", MODE_APPEND);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name", userName.getText().toString());
editor.putString("password", password.getText().toString());
editor.commit();
但我发现新值覆盖了旧值.你会帮我解决这个问题吗?
But I found that new value overwrites the old value. Will you help me to fix this issue?
推荐答案
MODE_APPEND
并不意味着您为每个键添加多个值.这意味着如果文件已经存在,它会被附加到 并且不会被删除.我们通常使用MODE_PRIVATE
.
MODE_APPEND
doesn't mean that you add multiple values for each key. It means that if the file already exists it is appended to and not erased . We usually used MODE_PRIVATE
.
关于保存多个名称和密码,可以看看putStringSet(string key Set
方法.
As for saving multiple names and passwords, you can take a look at putStringSet(string key Set<String> values
Method.
您可以为每个键保存一组字符串值.您可以用一些特殊字符或字符串分隔用户名和密码.您甚至可以将对象序列化为 json.
You can save the for each key a set of string values. You can separate the username and password by some special character or string. You may even serialize an object to json.
所以基本上你需要做的是:
So basically what you need to do is:
- 从共享首选项中获取值列表
- 将当前值附加到列表中.
- 将列表保存回共享首选项.
这篇关于如何在Android的共享首选项中附加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!