0

我有一个 Persons 的 ArrayList (ArrayList<Person>),我想将该 ArrayList 存储在持久数据类型中。SharedPreferences 是一种解决方案,但它只是在操纵 String、int、float`... 变量。你有什么想法吗?非常感谢你。

4

3 回答 3

3

更简单的是使用 java Serialisation

你只需要一个 Persons 类:

public class Persons {

  ArrayList<Person> personList;
}

然后只需使用

// 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();

回读

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

缺点是在写入过程中会丢失电池电量。有些人先写入一个临时文件,删除旧文件并重命名为正确的文件名。

为了获得高性能(更少的空间,更快)你可以使用DataOutputStream,但是你必须自己编写所有字段(但这也很简单)

于 2012-12-03T18:48:18.710 回答
2

我会将Person数组中的每个存储为 SQLite 数据库中的一行。当您想将其读回程序中时,每一行都将成为Person数组中的一个对象。

于 2012-12-03T18:41:55.037 回答
1

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

于 2012-12-03T18:47:29.770 回答