简体   繁体   中英

Best approach to save permanently an ArrayList of a personalised type

I have an ArrayList of Persons (ArrayList<Person>) , I want to store that ArrayList in a persistent data type. SharedPreferences are a solution BUT it's just manipulating String, int, float`... variables. Do you have some ideas? Thank you very much.

I'd store each Person in the array as a row in an SQLite database. When you want to read it back into the program, each row becomes a Person object in the array.

Much simpler is to use java Serialisation .

You just need an Persons class:

public class Persons {

  ArrayList<Person> personList;
}

Then simply use

// init Persons
Persons person = new Persons();
// add some
persons.personList.add(new Person());

// write out
ObjectOutpuStream oos = new ObjectOutputStream(new BufferOutputStream(new FileOutputStream("personsDB.ser")));

oos.writeObject(persons);
oos.close();

read back with

ObjectInputStream ois = new ObjectInputStream(new BufferedInpuStream(new FileInpuStream("personsDB.ser")));
persons = (Persons) ois.readObject();
ois.close();
// ready! Java does that all for you; since Persons is one object which contains something

The disadvantage is when battery power is lost during writing. Some people write to a temporary file first, delete the old and rename to the correct file name.

For high performance (much less space, much faster) You could use DataOutputStream , but then you have to write all fields yourself (but this is simple too)

您必须使用数据库或将json响应写入文件并从文件中读取它

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM