Save an arraylist of Strings to shared preferences

后端 未结 4 1353
独厮守ぢ
独厮守ぢ 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:34

    If you can guarantee your Strings in ArrayList don't contain comma, you can simply use

    List<String> list = new ArrayList<String>();
    ...
    editor.putString(PREF_KEY_STRINGS, TextUtils.join(",", list));
    

    and to read the list

    String serialized = prefs.getString(PREF_KEY_STRINGS, null);
    List<String> list = Arrays.asList(TextUtils.split(serialized, ","));
    

    You are limited by the memory of the device. It's good practice to use background thread to read/write shared preferences.

    0 讨论(0)
  • 2020-12-10 14:41

    There is a method, putStringSet(), in SharedPreferences.Editor, which you can take advantage of if your strings are a Set. (That is, no duplicates).

    0 讨论(0)
  • 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<String> 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<size; i++)
            editor.remove(prefix+"_"+i);
    
        // write the current list
        for(int i=0; i<list.size(); i++)
            editor.putString(prefix+"_"+i, list.get(i));
    
        editor.putInt(prefix+"_size", list.size());
        editor.commit();
    }
    

    To retrieve it:

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

    And to actually use it:

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

    And to retrieve it:

    List<String> animals = readList (someContext, "animal");
    

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

    0 讨论(0)
  • 2020-12-10 14:59

    I suggest you to save the arraylist as Internal Storage File in Android. For example for a arraylist named text_lines:

    Internal storage File IO (Writing) :

    try {
       //Modes: MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITABLE
       FileOutputStream output = openFileOutput("lines.txt",MODE_WORLD_READABLE);
       DataOutputStream dout = new DataOutputStream(output);
       dout.writeInt(text_lines.size()); // Save line count
       for(String line : text_lines) // Save lines
          dout.writeUTF(line);
       dout.flush(); // Flush stream ...
       dout.close(); // ... and close.
    }
    catch (IOException exc) { exc.printStackTrace(); }
    

    Interal storage File IO (Reading) :

    FileInputStream input = openFileInput("lines.txt"); // Open input stream
    DataInputStream din = new DataInputStream(input);
    int sz = din.readInt(); // Read line count
    for (int i=0;i<sz;i++) { // Read lines
       String line = din.readUTF();
       text_lines.add(line);
    }
    din.close();
    
    0 讨论(0)
提交回复
热议问题