Search code examples
javaandroidarraylistserializable

Write and then read ArrayList<Object> from file across sessions on Android?


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.


Solution

  • 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.