Save an arraylist of Strings to shared preferences

后端 未结 4 1409
独厮守ぢ
独厮守ぢ 2020-12-10 14:00

What is the best way to save an ArrayList of strings to SharedPreferences in API level 8? The only way i can think of now is to save all of the str

4条回答
  •  春和景丽
    2020-12-10 14:51

    If you are using an api (like level 8) where you cant use put/getStringSet(), then this is a possible solution, but this is very expensive and not flexible if you want to store bigger lists. I mean creating a map like datastructure for a simple array-like structure creates a huge overhead, if preformance is important.

    To save it:

    public static void writeList(Context context, List list, String prefix)
    {
        SharedPreferences prefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
    
        int size = prefs.getInt(prefix+"_size", 0);
    
        // clear the previous data if exists
        for(int i=0; i

    To retrieve it:

    public static List readList (Context context, String prefix)
    {
        SharedPreferences prefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
    
        int size = prefs.getInt(prefix+"_size", 0);
    
        List data = new ArrayList(size);
        for(int i=0; i

    And to actually use it:

    List animals = new ArrayList();
    animals.add("cat");
    animals.add("bear");
    animals.add("dog");
    
    writeList(someContext, animals, "animal");
    

    And to retrieve it:

    List animals = readList (someContext, "animal");
    

    If you are not limited to use SharedPreferences, consider using SQLiteDatabase!

提交回复
热议问题