0

I put the String in SharedPreferences like this

SharedPreferences preferences = getActivity().getSharedPreferences("Music_playlist", Context.MODE_PRIVATE);

                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putString(Song_name, Song_name);
                        editor.commit();

and when i try to retrieve Strings from SharedPreferences it doesn't Maintain the same order as it is stored in sharedPreferences

 SharedPreferences prefs = getActivity().getSharedPreferences("Music_playlist", Context.MODE_PRIVATE);
    Map<String,?> keys = prefs.getAll();

    if(keys!=null) {

        for (Map.Entry<String, ?> entry : keys.entrySet()) {
            Log.d("data ADDED",(String)entry.getValue());
            PLAYLIST.add((String)entry.getValue());
        }
    }

how should i store Strings in SharedPreferences and Maintain the order while getting the Strings from it

shakil.k
  • 1,623
  • 5
  • 17
  • 27
  • 1
    Either serialize a list under a single preference key, or use a database. SharePreferences are not an ordered data store. – Dave Morrissey Jul 17 '14 at 19:15

1 Answers1

1

SharedPreferences are like a HashMap and don't give you any ordering of the key-value pairs you store in them. To store your playlist in an ordered way you'll need to use a single key value pair, and the value should be a comma separated list of song names. You can actually use any suitable separator character (taking care to escape the song names) or store a JSON encoded array.

Here's some pseudo code, but this doesn't illustrate best practice.

SharedPreferences preferences = getActivity().getSharedPreferences("Music_playlist", Context.MODE_PRIVATE);
String playlist = preferences.getString("playlist");
playlist += "," + escapeCsv(songName);

SharedPreferences.Editor editor = preferences.edit();
editor.putString("playlist", playlist);
editor.commit();

It may be better to store the playlist in a database instead.

Dave Morrissey
  • 4,371
  • 1
  • 23
  • 31