将其写入内部存储是一种解决方案。您可以将以下内容用作 Util 类中的静态方法:
检索 ArrayList:
final static String OBJECT_1_LIST = "object_1_list";
static ArrayList<MyObject1> object1List = null;
static ArrayList<MyObject1> getObject1List(Context mContext) {
FileInputStream stream = null;
try {
stream = mContext.openFileInput(OBJECT_1_LIST);
ObjectInputStream din = new ObjectInputStream(stream);
object1List = (ArrayList<MyObject1>) din.readObject();
stream.getFD().sync();
stream.close();
din.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
if (object1List == null) {
object1List = new ArrayList<MyObject1>();
}
return object1List;
}
同样,要更新 ArrayList:
private static void updateObject1List(Context mContext) {
FileOutputStream stream = null;
try {
stream = mContext.openFileOutput(OBJECT_1_LIST,
Context.MODE_PRIVATE);
ObjectOutputStream dout = new ObjectOutputStream(stream);
dout.writeObject(object1List);
stream.getFD().sync();
stream.close();
dout.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
要添加项目:
static void addToObject1list(Context mContext, MyObject1 obj) {
Utilities.getObject1List(mContext).add(obj);
Utilities.updateObject1List(mContext);
}
添加用于删除项目和清除 ArrayList 的方法。
您还需要MyObject1
实施Serializable
:
public class MyObject1 implements Serializable {
....
....
}