Save an arraylist of Strings to shared preferences

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

提交回复
热议问题