我知道有在Android应用程序中保存数据的一些方法,但我想知道什么是最简单的和/或最有效的,或者换句话说哪种方法会赢得出复杂性的规模/理性/性能。
I know there are a few methods for saving data in an android application, but I'm wondering what is the simplest and/or most effective, or in other words which method would win-out on a scale of complexity/rationality/performance.
基本上我只是有两个班的ArrayList(类对象,而不是基本数据类型的ArrayList)。一个ArrayList中的对象的构造函数有三个整数,其他四个。基本上,我需要存储这些整数的值(我为每个设置返回整数方法无论是作为字符串或整数)用什么,告诉每一个属于的方式。
Basically I just have two Class ArrayLists (ArrayLists of class objects, not primitive data types). One ArrayList's object's constructor takes three integers,the other four. I basically need to store the value of those integers (I have methods for each set up to return the integers either as strings or ints) with a way of telling what each one belonged to.
举例来说,如果我有: arrayListOne.get(1).getNumbers()返回1,2,3 arrayListTwo.get(1).getNumbers()返回1,2,3,4
For instance, if I have: arrayListOne.get(1).getNumbers() returning 1, 2, 3 arrayListTwo.get(1).getNumbers() returning 1, 2, 3, 4
这将返回不同数量等指标的一大堆,我怎么能存储数据,因此当应用程序被关闭并重新启动它重新加载和值忠于他们在被初始化索引?
and a whole heap of other indexes that would return different numbers, how can I store that data so when the app is closed and restarted it is reloaded and the values stay true to the indexes they were initialized at?
推荐答案
它写入到内部存储是一个解决方案。您可以使用以下内容作为的Util类中的静态方法:
Writing it to internal storage is one solution. You can use the following as a static method inside a Util class:
检索的ArrayList
Retrieve the 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
Similarly, to update the 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
Add methods for removing an item and clearing the ArrayList.
您还需要 MyObject1
实施序列化
:
public class MyObject1 implements Serializable {
....
....
}
相关推荐
最新文章