I want to store an arraylist of objects in a file in order to reach them after the app is opened again.
public class SmsMessage implements Serializable {
public 开发者_开发知识库static enum MessageType {
Sent,
Received;
};
private String body;
private Date date;
private MessageType type;
public SmsMessage(String _body, Date _date, MessageType _type) {
body = _body;
date = _date;
type = _type;
}
}
That's the whole class. I'm saving it like this:
FileOutputStream fout = null;
ObjectOutputStream out = null;
try {
fout = context.getApplicationContext()
.openFileOutput(FILENAME, Context.MODE_PRIVATE);
out = new ObjectOutputStream(fout);
out.writeObject(list);
out.close();
} catch (IOException ioe) {
System.out.println("Error in save method");
} finally {
out.close();
fout.close();
}
and read it like this:
ObjectInputStream in = null;
FileInputStream fis = null;
try {
fis = context.getApplicationContext().openFileInput(FILENAME);
in = new ObjectInputStream(fis);
ArrayList<SmsMessage> list = null;
list = (ArrayList<SmsMessage>)in.readObject();
} catch (Exception ex) {
System.out.println("Error in get method");
} finally {
in.close();
fis.close();
}
This code doesn't work - I mean when I'm saving a full arraylist and kill the app, it returns nothing when I'm trying to read it again when the application is opened. What's wrong here?
Initialise like this:
fout=new FileOutputStream(FILENAME));
after out.writeObject(list); add this line
out.flush();
similarlly initialise
fis = new FileInputStream((FILENAME));
Hope this works....r u getting any error message on logcat??
精彩评论