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.
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 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With