Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put and get String array from shared preferences

I need to save on shared preferences some array of Strings and after that to get them. I tried this :

prefsEditor.putString(PLAYLISTS, playlists.toString()); where playlists is a String[]

and to get :

playlist= myPrefs.getString(PLAYLISTS, "playlists"); where playlist is a String but it is not working.

How can I do this ? Can anyone help me?

Thanks in advance.

like image 977
Gabrielle Avatar asked Nov 01 '11 10:11

Gabrielle


People also ask

Can we store array in SharedPreferences?

You can save String and custom array list using Gson library. =>First you need to create function to save array list to SharedPreferences. public void saveListInLocal(ArrayList<String> list, String key) { SharedPreferences prefs = getSharedPreferences("AppName", Context. MODE_PRIVATE); SharedPreferences.

How do I pass data from one activity to another using SharedPreferences?

How to pass data from one activity to another in Android using shared preferences? Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How can I get SharedPreferences value?

getBoolean(String key, boolean defValue): This method is used to retrieve a boolean value from the preferences. getFloat(String key, float defValue): This method is used to retrieve a float value from the preferences. getInt(String key, int defValue): This method is used to retrieve an int value from the preferences.


1 Answers

You can create your own String representation of the array like this:

StringBuilder sb = new StringBuilder(); for (int i = 0; i < playlists.length; i++) {     sb.append(playlists[i]).append(","); } prefsEditor.putString(PLAYLISTS, sb.toString()); 

Then when you get the String from SharedPreferences simply parse it like this:

String[] playlists = playlist.split(","); 

This should do the job.

like image 93
Egor Avatar answered Sep 25 '22 08:09

Egor