Mario Teixeira
Mario Teixeira

Reputation: 15

Save arraylist of objects and reading it from file

I have an arraylist of objects in a fragmentActivity

private List<Movie> myMovies = null;

I have options to add, remove and all that from the movie list, but once I close the application all is lost. How can I save the array into a file and retrieve the array from the file?

I have:

public void writeArray() {
    File f = new File(getFilesDir()+"MyMovieArray.srl");
    try {
        FileOutputStream fos = new FileOutputStream(f);
        ObjectOutputStream objectwrite = new ObjectOutputStream(fos);
        objectwrite.writeObject(myMovies);
        fos.close();

        if (!f.exists()) {
            f.mkdirs();
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 public ArrayList<Movie> read(Context context) {

      ObjectInputStream input = null;
      ArrayList<Movie> ReturnClass = null;
      File f = new File(this.getFilesDir(),"MyMovieArray");
      try {

       input = new ObjectInputStream(new FileInputStream(f));
       ReturnClass = (ArrayList<Movie>) input.readObject();
       input.close();

      } catch (StreamCorruptedException e) {
       e.printStackTrace();
      } catch (FileNotFoundException e) {
       e.printStackTrace();
      } catch (IOException e) {
       e.printStackTrace();
      } catch (ClassNotFoundException e) {
       e.printStackTrace();
      }
      return ReturnClass;
     }

but it is not working. getFilesDir() always points to a nullpointerexception Is this the right way to do it? Any sugestions on how can I save the array into a file and retrieve the array from the file?

UPDATE 1: Found the fix, just needed to write File f = new File(getFilesDir(), "MyMovieArray.srl"); New problem arrised: I have this code for onCreate:

myMovies = read(this);
    if(myMovies==null){
        myMovies = new ArrayList<Movie>();
        populateMovieListWithExamples();
        writeArray();
    }

Everytime I start the application it always shows the list with the populate examples... if I add or remove once I reopen it is always the same list. Sugestions?

UPDATE 2 Just needed Movie class to be serializable. Thank you all for your help. Have a good day everyone

Upvotes: 0

Views: 717

Answers (2)

Jayesh Elamgodil
Jayesh Elamgodil

Reputation: 1477

Use File f = new File(getFilesDir(), "MyMovieArray.srl");

in both writeArray() and read() methods

Upvotes: 1

Carnal
Carnal

Reputation: 22064

You are saving to MyMovieArray.srl but reading from MyMovieArray. Read also from MyMovieArray.srl

File object should be created like this (both in write and read):

File f = new File(getFilesDir(), "MyMovieArray.srl");

Upvotes: 1

Related Questions