Does s开发者_JS百科omeone know how to save and restore an object to a file on android ?
Open a file using openFileOutput() ( http://developer.android.com/guide/topics/data/data-storage.html#filesInternal ), than use an ObjectOutputStream ( http://download.oracle.com/javase/1.4.2/docs/api/java/io/ObjectOutputStream.html ) to write your object to a file.
Use their evil twin openFileInput() and ObjectInputStream() to reverse the process.
It depends if You want to save file on internal or external media. For both situation there are great samples on Android DEV site: http://developer.android.com/guide/topics/data/data-storage.html - this should definetly help
Here is a tested example of @yayay's suggestion. Note that using readObject()
returns an Object
, so you will need to cast, although the compiler will complain that it is an unchecked cast. I can still run my code fine though. You can read more about the casting issue here.
Just make sure that your class (in my case, ListItemsModel
) is serializable, because the writeObject()
will serialize your object, and the readObject()
will deserialize it. If it is not (you get no persistence and the logcat throws a NotSerializableException
), then make sure your class implements java.io.Serializable
, and you're good to go. Note, no methods need implementing in this interface. If your class cannot implement Serializable
and work (e.g. 3rd party library classes), this link helps you to serialize your object.
private void readItems() {
FileInputStream fis = null;
try {
fis = openFileInput("groceries");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<ListItemsModel> list = (ArrayList<ListItemsModel>) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
private void writeItems() {
FileOutputStream fos = null;
try {
fos = openFileOutput("groceries", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(itemsList);
} catch (IOException e) {
e.printStackTrace();
}
}
精彩评论