skip to Main Content

I’ve been trying to do this for a while but I didn’t find any solution.

I’m working on a shopping list app for android and I have an arraylist of items. I want to write it into a file which will be read everytime the app is opened, to save changes of it. I have a method to write the arraylist, which is this one:

File path = getApplicationContext().getFilesDir();
    try {
        FileOutputStream fos = new FileOutputStream("output");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(items);
        oos.close();
    } catch(Exception ex) {
        ex.printStackTrace();
    }

However I tried many things to read the file and none seem to work. What can I do?

2

Answers


  1. Chosen as BEST ANSWER

    Found the solution. I read the arraylist with this:

    public void loadContent(){

        File path = getApplicationContext().getFilesDir();
        File readFile = new File(path,"output.txt");
        
    
        try {
    
            FileInputStream readData = new FileInputStream(readFile);
            ObjectInputStream readStream = new ObjectInputStream(readData);
            ArrayList<Item> aux = (ArrayList<Item>) readStream.readObject();
            readStream.close();
            items = aux;
    
            adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_multiple_choice,items);
    
            elementsList.setAdapter(adapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    
    
    }
    

  2. In java, you can use a try-witch-resource block.This makes sure that you close the file of something goes wrong. I use BufferReader when I want to read from a while.

    In this code snippet, I store each line in an arraylist:

    ArrayList<String> lines;
    

    Then you iterate through the file:

    try(BufferedReader reader = Files.newBufferedReader(path)) {
            String line;
            while((line = reader.readLine())!= null){ //while there is a next line..
                lines.add(line);
            }
        } catch (IOException e) {
            /* File does not exits. */
            throw new IllegalArgumentException("File not found");
        }
    

    I recommend watching a youtube video, or reading on the javadoc for the buffer reader.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search