Search code examples
javaandroidsqliteandroid-sqlite

Different types of users logging in to Android App with SQLite Database


Sorry if this is a stupid question but I am new to Android Development. I am trying to create a login screen which will direct doctors to a one activity and nurses to another activity when they login. This does not seem to work. I have put code into the login.java class:

btLogin.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                String email = loginemail.getText().toString();
                String password = loginpassword.getText().toString();
                Boolean Chkemailpass = db.emailpassword(email, password);
                if(Chkemailpass == true) {
                    Cursor typeofuser;
                    typeofuser = db.checkUser(loginemail.getText().toString()); //get user type from database
                    if(typeofuser.equals("Nurse")) {
                        Intent mainintent = new Intent(Login.this, NurseHome.class);
                        startActivity(mainintent);}
                    else if (typeofuser.equals("Doctor")){
                        Intent intent = new Intent(Login.this, DoctorHome.class);
                        startActivity(intent);}
                    }
                    else
                    Toast.makeText(getApplicationContext(),"Wrong email or password", Toast.LENGTH_SHORT).show();
                }
        });

    }
}

And I also have this code in the databasehelper class relating to the usertype:

public Cursor checkUser(String email) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("SELECT TYPEOFUSER from user_table WHERE EMAIL=email", null);
        return res;
     }

All help would be appreciated, thank you.


Solution

  • The argument email of checkUser() is a string, so in your sql statement it should be enclosed inside single quotes like this:

    SELECT TYPEOFUSER from user_table WHERE EMAIL = 'email'
    

    but the correct way to pass parameters to rawQuery() is with the use of ? placeholders and the use of the 2nd argument as an array of string parameters (instead of null).
    Also don't return the Cursor, but the type of user as a String from checkUser().
    So change to this:

    public String checkUser(String email) {
        String result = "";
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery(
            "SELECT TYPEOFUSER from user_table WHERE EMAIL = ?", 
            new String[] {email}
        );
        if (res.moveToNext()) {
            result = res.getString(0);
        }
        res.close();
        return result;
    }
    

    and instead of:

    Cursor typeofuser;
    typeofuser = db.checkUser(loginemail.getText().toString());
    

    use this:

    String typeofuser = db.checkUser(loginemail.getText().toString());