how to append data in Shared Preference in Android

醉酒当歌 提交于 2019-12-13 09:23:27

问题


I tried to append the data in shared preference file by using

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?


回答1:


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.

As for saving multiple names and passwords, you can take a look at putStringSet(string key Set<String> values Method.

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:

  1. Get the list of values from Shared Preferences
  2. Append the current value to the list.
  3. Save the List back to Shared Preferences.


来源:https://stackoverflow.com/questions/38560117/how-to-append-data-in-shared-preference-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!