Search code examples
androidhashmapsetsharedpreferencesentryset

How to retrieve Strings from SharedPreferences in the same order as it is stored


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


Solution

  • 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.