0

I am trying to save the history of videos watched in my app but i am unable to retrieve the order in which the videos were watched , the order is all messed up here is the code i am using to save the arraylist

 public void SaveHistory(Context context,String url,boolean save)
{
    FetchHistory(context);
    if(save)
    {
        pathList.add(url);
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        LinkedHashSet<String> set = new LinkedHashSet<>(pathList);
        sharedPreferences.edit().putStringSet("History",set).apply();

    }
    else
    {
        pathList.remove(url);
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        LinkedHashSet<String> set = new LinkedHashSet<>(pathList);
        sharedPreferences.edit().putStringSet("History",set).apply();
    }

}

and this is the code i am using to retrieve array list

 public ArrayList<String> FetchHistory(Context context)
{
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    Set<String> newSet =  sharedPreferences.getStringSet("History",null);
    if(newSet!=null)
    {
        pathList.clear();
        pathList.addAll(newSet);
        Collections.reverse(pathList);
    }
    return pathList;
}
  • Does this answer your question? [Misbehavior when trying to store a string set using SharedPreferences](https://stackoverflow.com/questions/14034803/misbehavior-when-trying-to-store-a-string-set-using-sharedpreferences) – ariefbayu Mar 21 '20 at 09:16
  • Also this: https://stackoverflow.com/a/13446387/156869 – ariefbayu Mar 21 '20 at 13:24

1 Answers1

1

I think the following code is the problem: sharedPreferences.getStringSet

You may get an HashSet which is not ordered. Try to store it in another way.

Edit: A fast but not very fancy solution would be to store the items in a concatenated string with a specific separator.

For a better solution you may have to use another technique to store preferences.

Tobi
  • 100
  • 9