Saving Serializable Objects List into sharedPreferences

前端 未结 5 1068
闹比i
闹比i 2020-12-03 05:10

Can anyone tell me how I can save a list of custom Serializable objects into SharedPreference? I am new To Android and I want to save an Arr

5条回答
  •  借酒劲吻你
    2020-12-03 05:56

    You can use the JSON format to serialize your ArrayList and the objects it contains, and then store the String result into the SharedPreferences.

    When you want to get the data back, retrieve the String and use a JSONArray to retrieve each object and add it to a new ArrayList.

    Otherwise you can simply use Object(Input/Output)Stream classes and write it into a differente file using (for writing)

    FileOutputStream fos = this.openFileOutput(fileName, MODE_PRIVATE);
    final OutputStreamWriter osw = new OutputStreamWriter(fos);
    JSONArray array = new JSONArray();
    
    // Add your objects to the array
    
    osw.write(array.toString());
    osw.flush();
    osw.close();
    

提交回复
热议问题