Search code examples
javaarraylistnullpointerexceptionhashmapnull-pointer

NullPointerException error in Hashmap


I have spent countless hours on this one part of my code which is giving me a Null Pointer Exception. I do not understand why it is happening or how to stop it. I have tried every method previously posted on stackoverflow. Here is the function that reads a data file and puts each line in a hashmap.

public ArrayList<HashMap<String, String>> readDataFromFile(){
    this.openFileForReading();
    ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
    try{
        String line;

        while ((line = this.reader.readLine()) != null){ 

            while (!(line.equals(""))){

                if (line.equals("[type = book]")){
                    HashMap<String, String> data= new HashMap<>();
                    line = this.reader.readLine();

                    while (!(line.equals(""))){<----this is where the null exception error is

                        String tokens[] = line.split("=");
                        data.put(tokens[0], tokens[1]);
                        System.out.println(tokens[0] + " " + tokens[1]);
                        line = this.reader.readLine();

                    }
                   list.add(data);
                }
                else{
                    break;
                }
            }

        }
    }
    catch (IOException exception) {
        list = null;
        System.err.println("(FileIO): " + exception);            
    }
    // Close the file when we have finished reading or if an error occurs
    finally {
        try {
            this.reader.close();                
        } catch (IOException exception) {
            System.err.println("(FileIO): " + exception);
        }
    }

    return list;
}

I then run it in main with this:

public static void main (String args[]) {                                
    FileIO fileIO = new FileIO(DATA_FILE_PATH);
    ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
    list = fileIO.readDataFromFile();

}
run:

callnumber �QA76.73.J38S265� authors �Walter Savitch, Kenrich Mock� title �Absolute Java� publisher �Addison-Wesley� year �2009� callnumber �P98.C6116� title �Computational Linguistics� Exception in thread "main" java.lang.NullPointerException organization �Association for Computational Linguistics� at librarysearch.FileIO.readDataFromFile(FileIO.java:160) year �2008� at librarysearch.FileIO.main(FileIO.java:405) Java Result: 1 BUILD SUCCESSFUL (total time: 1 second)

I wrote in the code where the error occurs. Why is this happening? I don't understand, if anyone saavy could please help that would be greatly appreciated.


Solution

  • You're consuming a new line without checking for null:

     HashMap<String, String> data= new HashMap<>();
     line = this.reader.readLine(); <--- i mean this, and line can be null
    
     while (!(line.equals(""))){<----this is where the null exception error is
    

    I give you a general advise:

    Never compare a String variable against a String literal in this way:

    if (myStringWhichCanBeNull.equals("my literal which is never null")) // ...
    

    but always like this:

    if ("my literal which is never null".equals(myStringWhichCanBeNull)) // ...
    

    In many cases you will avoid NPE and have more robust code!

    (I don't say that in this case this had saved your live...)