Nicklas O
Nicklas O

Reputation: 23

Serializing ArrayList android not working

UPDATE: After a bit of testing I've determined the file itself isnt being created, at least according to the file.exists check anyway. Any ideas?

Hi I'm trying to serialize an arraylist when my app is exited and read it back when its resumed. It doesnt seem to be creating the file.

Here is my code.

protected void onPause() {
    super.onPause();

    if(!myArrayList.isEmpty())
    {
        final String FILENAME = "myfile.bin";
        try{
            FileOutputStream fos;

            fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);

            //FileOutputStream fileStream = new FileOutputStream(FILENAME);
            ObjectOutputStream os = new ObjectOutputStream(fos);
            os.writeObject(myArrayList);
            os.flush();
            os.close();
        } catch (FileNotFoundException e) {
                e.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
    }
}

@SuppressWarnings("unchecked")
    @Override
    protected void onResume() {
        super.onResume();

    File file = new File("myfile.bin");
    if(file.exists()){
        final String FILENAME="myfile.bin";
        try{
            FileInputStream fileStream = new FileInputStream(FILENAME);
            ObjectInputStream os = new ObjectInputStream(fileStream);
            myArrayList = (ArrayList<MyObject>)os.readObject();
            os.close();
        } catch (FileNotFoundException e) {
                e.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
        }
    }




}

Any ideas? My MyObject class implements serializable.

Upvotes: 0

Views: 1755

Answers (2)

Nicklas O
Nicklas O

Reputation: 23

Got it to work by changing FileInputStream fileStream = new FileInputStream(FILENAME) to FileInputStream fileStream= openFileInput(FILENAME).

Upvotes: 1

Naveen
Naveen

Reputation: 116

os.writeObject(myArrayList);
os.flush();
os.close();

Try os.close() immediately after writeObject, it should call flush() anyways.

Upvotes: 0

Related Questions