简体   繁体   中英

How to store multiple data into SharedPreference

i have this

 mSharedPref.edit().putString("newuser",model.getName()).apply();

and this is where im retrieving the data in my onStart() method

Log.e("ONSTARTUSER",""+ mSharedPref.getString("newuser",null));

my output is this

ONSTARTUSER: Homer Simpson

but i have a collection of names, lets say like 10 names , and i want my shared preferences to display them all when i call the getString("newuser") , how can i do this ? im using firebaselistadapter

First convert your list to a set:

Set<String>usersSet= new HashSet<>(usersList);

Then save the set into SharedPreferences:

    SharedPreferences prefs = getSharedPreferences();
    SharedPreferences.Editor editor = prefs.edit();
    editor.putStringSet("newusers", usersSet);

And to get them:

    SharedPreferences prefs= getSharedPreferences();
    Set<String> usersSet= prefs.getStringSet("newusers", new HashSet<String>());

Two alternatives : use a StringSet with editor.putStringSet() or use a SQLite database.

The database seems the best solution for me to maintain a list of names (or a list of anything), more safe. If for example your app is killed by the system you can lose data with the Shared Prefs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM