如何为特定用户创建登录功能

时间:2019-10-09 15:00:14

标签: android sqlite android-sqlite

此应用程序可以注册2个主要用户的学生和老师。注册用户后,他们可以登录。如果用户是老师,则将重定向到教师活动;如果是学生,则将重定向到注册页面中的其他活动。学生和老师将被一个复选框选中。

这是我到目前为止尝试过的代码:

 String user = username.getText().toString();
                String pass = password.getText().toString();

                cursor = db.rawQuery("SELECT * FROM " + DatabaseHelper.TABLE_USER + " WHERE " + DatabaseHelper.NAME + "=? AND " + DatabaseHelper.PASSWORD + "=?", new String[]{user,pass});
                if(username.getText().toString().trim().length() == 0 ||
                        password.getText().toString().trim().length() == 0){
                    toast(MainActivity.this,"All fields are required");
                }
                else if (cursor != null){
                    if(cursor.getCount() > 0){
                        if(cursor.getString(cursor.getColumnIndex(TYPE)).equals("Teacher")){
                            view_teacher();
                            toast(MainActivity.this,"Welcome " + username.getText().toString().toUpperCase());
                        }
                        else{
                            view_student();
                            toast(MainActivity.this,"Welcome " + username.getText().toString().toUpperCase());
                        }
                    }
                    else {
                        toast(MainActivity.this,"Username or Password invalid");
                    }
                }
                else{
                    toast(MainActivity.this,"Error Login in");
                }
            }
        });

这就是注册功能的样子

}else if (db.registeruser(username.getText().toString(), password.getText().toString(),teacher.isChecked() ? "Teacher" : (student.isChecked() ? "Student" : "N/A"))){
                    loginScreen();
                    toast(Register.this,"Successfully Registered Please Login");
                }

当我尝试执行登录功能时,应用程序将崩溃

1 个答案:

答案 0 :(得分:0)

您没有发布错误日志,但是我认为您抛出的错误是因为您在尝试访问cursor.moveToFirst()返回的行之前没有调用并检查rawQuery(),因此光标的位置在第一行之前。
还将呼叫移至rawQuery()块内的else

String user = username.getText().toString().trim();
String pass = password.getText().toString().trim();

if(user.length() == 0 || pass.length() == 0){
    toast(MainActivity.this,"All fields are required");
} else {
    cursor = db.rawQuery("SELECT * FROM " + DatabaseHelper.TABLE_USER + " WHERE " + DatabaseHelper.NAME + "=? AND " + DatabaseHelper.PASSWORD + "=?", new String[]{user,pass});
    if(cursor.moveToFirst()) {
        if(cursor.getString(cursor.getColumnIndex(TYPE)).equals("Teacher")){
            view_teacher();
        } else {
            view_student();
        }
        toast(MainActivity.this,"Welcome " + username.getText().toString().toUpperCase());
    } else {
        toast(MainActivity.this,"Username or Password invalid");
    }
}