0
votes

Hi im trying to save my ArrayList of objects to a file when onPause() and/or onStop() are called and then have the arrayList read from that file after the app has been killed and relaunched. Ive tried a load of different methods but none seem to work, currently this is what I have.

my code to Write :

 try{
        FileOutputStream fout = openFileOutput(FILENAME, 0);
        ObjectOutputStream oos = new ObjectOutputStream(fout);
        oos.writeObject(toDos);
        oos.close();
    }
    catch (Exception e){
        e.printStackTrace();
    }

My code to Read :

 try{
        FileInputStream streamIn = openFileInput(FILENAME);
        ObjectInputStream ois = new ObjectInputStream(streamIn);
        if(ois.readObject() != null) {
            list = (ArrayList<Object>) ois.readObject();
            ois.close();
        }
    }
    catch (Exception e){
        e.printStackTrace();
    }

"FILENAME" is a variable that holds the string "data.txt" toDos is the name of the arrayList, it is a field at the top of the Activity, it is an ArrayList of object Object which is Serializable.

Not sure what im doing wrong here, and I cant tell if its writing at all or not or where the issue might be.

1
What error are you getting?Thomas
@Thomas None at all it just doesnt do as required. Unless I try to have a File x = new File(this.getFileDirs(),FILENAME) then I get a null pointer exception.Volt
It's considered a bad practice to use a catch statement to catch a general Exception, please make separate catch statements for FileNotFoundException, IOException, and ClassNotFoundException, and then see which type of exception the try block is catching.Thomas
@Thomas I was tinkering with it, turns out its throwing a EOFException when it tries to read the file, no errors appear to be returned from the write to file part.Volt

1 Answers

0
votes

You are getting an EOFException because you are reading in the object twice; once when you're checking the if statement, and once again inside the if statement. Change your code to something like this:

FileInputStream streamIn = openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(streamIn);
ToDoObject tmp = (ArrayList<ToDoObject>) ois.readObject();
ois.close();
if(tmp != null) {
    toDos = tmp;
}

This code accomplishes the same thing but reads from the file a single time.