-3

My login works fine when I enter the correct username and password and it starts a new activity. But for some reason when I enter incorrect username and password it doesn't proceed and the app just crashes.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myDB = new DBHelper(this);

    EditText txtUser = (EditText) findViewById(R.id.txtUser);
    EditText txtPassword= (EditText) findViewById(R.id.txtPassword);

    Button btnLogin = (Button) findViewById(R.id.btnAdminLogin);
    Button btnCreateAcc = (Button) findViewById(R.id.btnCreateAcc);
    Button btnAdmin = (Button) findViewById(R.id.btnAdmin);

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            u = new User();
            String username = txtUser.getText().toString();
            String pass = txtPassword.getText().toString();

            u = myDB.readUser(username);

            if(u.getUser().equals(username) && u.getPass().equals(pass)){
                Intent menu = new Intent(getApplicationContext(), MainMenu.class);
                startActivity(menu);
            }
            else {
               Toast.makeText(MainActivity.this, "Incorrect username or password!" + pass, Toast.LENGTH_SHORT).show();
            }

        }
    });

This is in my DBhelper, readUser.

public User readUser(String user){
    SQLiteDatabase db = this.getReadableDatabase();
    User u =null;
    String where =  col_uname + " = ?";
    String[] selectionArgs = {user};
    Cursor cursor =db.query("tblUser", null, where, selectionArgs, null, null, null);

    try {
        if(cursor.moveToNext()) {
            u = new User();
            u.setUser(cursor.getString(0));
            u.setPass(cursor.getString(4));
            u.setFname(cursor.getString(1));
            u.setMname(cursor.getString(2));
            u.setLname(cursor.getString(3));
            u.setMobile(cursor.getString(6));
            u.setCity(cursor.getString(5));
        }
    } catch(Exception ex) {}

    db.close();
    return u;
}

I don't know what I did wrong with my if/else statement. Pls help.

SwissCodeMen
  • 4,222
  • 8
  • 24
  • 34
aash_dl8
  • 1
  • 2

1 Answers1

0

You read out the user from the database, and if this user is found, a user object is returned, otherwise null.

u = myDB.readUser(username);

So if the user is not found, your u is null. Thus a NullPointerException will occur. Also see What is a NullPointerException, and how do I fix it?

So before accessing methods of User, check that u is not null.

u = myDB.readUser(username);

if(u != null /* <- */ && u.getUser().equals(username) && u.getPass().equals(pass)){
  // ...
} else {
  // Toast.makeText(MainActivity.this, "Incorrect username or password!" + pass, Toast.LENGTH_SHORT).show();
}
Daniel
  • 1,426
  • 1
  • 11
  • 24