infamoustrey
infamoustrey

Reputation: 718

Android: Reading a text file and storing to an ArrayList<String>

So I am attempting to read from a file in android. I initialize everything yet I still get a NullPointerException. Am I missing something?

Error is recieved at line 25.

public class Read {
    private ArrayList<String> contents;
    private final String filename = "saves/user.txt";

    public Read(Context context) {
        try {
            contents = new ArrayList<String>();
            InputStream in = context.getAssets().open(filename);

            if (in != null) {
                // prepare the file for reading
                InputStreamReader input = new InputStreamReader(in);
                BufferedReader br = new BufferedReader(input);
                String line = br.readLine();
                while (line != null) {
                    contents.add(line);
                }
                in.close();
            }else{
                System.out.println("It's the assests");
            }

        } catch (IOException e) {
            System.out.println("Couldn't Read File Correctly");
        }
    }

    public ArrayList<String> loadFile() {
        return this.contents;
    }
}

Upvotes: 5

Views: 3524

Answers (1)

Deepzz
Deepzz

Reputation: 4571

Do like this

 while ((line=reader.readLine()) != null) 
 {
    contents.add(line);
 }

Upvotes: 4

Related Questions