Search code examples
androidfor-looptextfileinputstream

Trying to loop through txt file contents gives error


I am attempting to loop through many text files and make an array with the first 25 characters from each file. I would also like the word empty to be put in if the file doesn't exist. I thought my code would work, but I seem to be running in to some issues. Can you read through it and see what might be wrong?

try {



        // Loop through files
         List<String>[] results = new List[filenamearray.length];

          for (int i = 0; i < filenamearray.length; i++) {

        File txt = new File(getExternalFilesDir(Environment.DIRECTORY_MUSIC) + "/" + filenamearray[0] + ".txt");
        if (txt.exists()) {

            // Open the file with a FileReader
            txtread = new FileInputStream(getExternalFilesDir(Environment.DIRECTORY_MUSIC) + "/" + filenamearray[0] + ".txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader(txtread));
            String text = reader.readLine();
            displaytxt = text.substring(0, 25) + "...";

                results[i].add(displaytxt);

        } else {
            Log.i(TAG, "file does not exists");

            results[i].add("empty");

        }
    }


        finalarrangedlist = new ArrayList<>(filenamearray.length);
        for (List<String> result : results) {
            if (result != null) {
                finalarrangedlist.addAll(result);
            }else{Log.i(TAG, "result is null");}
        }
        finalversetextarray = new String[finalarrangedlist.size()];
        finalversetextarray = finalarrangedlist.toArray(finalversetextarray);

    } catch (Exception e) {
        e.printStackTrace();
    }

The error I'm getting is this:

W/System.err: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference

Solution

  • your code is very wrong. first, you're not loopingg for every text file on your dir, but only one file. look at this line

        File txt = new File(getExternalFilesDir(Environment.DIRECTORY_MUSIC) + "/" + filenamearray[0] + ".txt");
    

    it should be

        File txt = new File(getExternalFilesDir(Environment.DIRECTORY_MUSIC) + "/" + filenamearray[i] + ".txt");
    

    and the second mistake. you make an array of List, but on accessing it, you didn't make an instance of it. it should be a nullpointerexception from the start you accessing it. look at this line

         List<String>[] results = new List[filenamearray.length];
    

    and when you access it in this line

     results[i].add(displaytxt);
    

    you get a null pointer exception because result in index "i" are a null.

    I modified your code, try to use(I'm not try this yet, but it could help you to fix your problem)

    try {
    
        // Loop through files
    
        //you only need to use one arraylist to be able to store all the result from reading your files
        List<String> results = new ArrayList<String>();
        for (int i = 0; i < filenamearray.length; i++) {
    
            File txt = new File(getExternalFilesDir(Environment.DIRECTORY_MUSIC) + "/" + filenamearray[i] + ".txt");
            if (txt.exists()) {
    
                // Open the file with a FileReader
                txtread = new FileInputStream(getExternalFilesDir(Environment.DIRECTORY_MUSIC) + "/" + filenamearray[i] + ".txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(txtread));
                String text = reader.readLine();
                displaytxt = text.substring(0, 25) + "...";
    
                results.add(displaytxt);
    
            } else {
                Log.i(TAG, "file does not exists");
    
                results.add("empty");
    
            }
        }
        //this line of code I comment because it's not efficient
        /*
        finalarrangedlist = new ArrayList<>();
        for (List<String> result : results) {
            if (result != null) {
                finalarrangedlist.addAll(result);
            }else{Log.i(TAG, "result is null");}
        }
        finalversetextarray = new String[finalarrangedlist.size()];
        finalversetextarray = finalarrangedlist.toArray(finalversetextarray);
        */
    
        //just make results to an array string
        finalversetextarray = new String[results.size()];
        finalversetextarray = results.toArray(finalversetextarray);
    } catch (Exception e) {
        e.printStackTrace();
    }