Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Null Pointer Exception when using isEmpty() method

I'm trying to implement a login feature for my program but it's returning a null pointer exception. I understand that this happens when you refer to a place in memory that has nothing in it, but as far as I can see I have instantiated all my objects properly - please correct me if I am wrong!

I am trying to implement an add user feature: I have a list of usernames and passwords and I have an existing method which reads that file in and stores it in an array. I want to write a new login to the list so I wrote a new method which converts this array to an ArrayList and will eventually write a new login to it and then write the Login file out again. The problem is I am getting the Null Pointer Exception.

Method 1:

public String[] readFile(){
    ArrayList<String> dataList = new ArrayList<String>();
    String Line;
    try {
        String line = br.readLine();
        do {                
            dataList.add(Line);
            line = br.readLine();
        }
        while (!line.isEmpty());
        br.close ();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    String[] dataArr = new String[dataList.size()];
    dataArr = dataList.toArray(dataArr);

    return dataArr; // Returns an array containing the separate lines of the file
}

Method 2:

public void addNewUser (String username, String password){
    String[] dataArr = readFile();  // Read in the list of profiles and store it in an array
    ArrayList<String> dataAL = new ArrayList<String>(Arrays.asList(dataArr));   // store array of profiles as ArrayList
    dataAL.add(username + "\t" + password);

}
like image 406
user1058210 Avatar asked Dec 26 '11 19:12

user1058210


1 Answers

You are probably getting null pointer here

while (!line.isEmpty());

change it to

while(line!=null && !line.isEmpty())

If you paid attention to the exception's stack trace you should see the exact line where the exception is being raised

like image 96
Aravind Yarram Avatar answered Sep 28 '22 07:09

Aravind Yarram