I’ve written a method to check an inputed username and password with a text file with all the usernames and passwords. The interesting problem is that if the details are correct then the application progresses, but if the details are incorrect it returns a NullPointerException. My code is below:
// Checks whether the inputed details are correct
public boolean isCorrect(String u, String p) {
boolean check = false;
String line = null;
try {
do {
line = br.readLine();
// System.out.println("Checking profile : " + line);
String[] info = line.split("\t");
// nested if-statement to improve efficiency over &&
if (info[0].equals(u)) {
System.out.println("username found!");
if (info[1].equals(p)) {
System.out.println("password correct!");
check = true;
} else System.out.println("password incorrect!");
} else System.out.println("username not found!");
} while (line != null && check == false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return check;
}
The returned boolean value is entered into the following code in the main activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginpanel);
Button button = (Button) findViewById(R.id.btnLogin);
Correct = false;
lm = new LoginModel(this);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText textUsername = (EditText) findViewById(R.id.textUsername);
EditText textPassword = (EditText) findViewById(R.id.textPassword);
// Collect the login details entered by the user
String username = textUsername.getText().toString();
String password = textPassword.getText().toString();
// Check the application is registering the correct details
System.out.println(username + "\n" + password);
Correct = lm.isCorrect(username, password);
if (Correct) { // if details are correct then start main program
Intent intent = new Intent (LoginView.this, MenuListView.class);
startActivity(intent);
}
else System.out.println("Login is incorrect...");
}
});
}
What I don’t understand is why if Correct = true then it runs no problems, but if Correct = false it crashes the program producing a FATAL EXCEPTION: main, and then a NullPointerException – shouldn’t it simply output the the System.out.println.
When you get to the end of the file,
lineisnull.Therefore, you can’t call
split()in the nest line (pun intended).However, do not use this code. It is very wrong and will trivially leak passwords once released.