我正在使光标索引超出范围“索引0请求:大小为0”。它只是一个用户注册和登录应用程序。当没有匹配用户名和密码的用户时,我的应用程序正在崩溃。
以下是代码:
MainActivity.java
final SUSQLiteHelper dbhelper = new SUSQLiteHelper(this);
LoginData login = dbhelper.readOneUser(loginuname.getText().toString(), loginpwd.getText().toString());
if(login.getUname().toString().equals(loginuname.getText().toString()) &&
login.getPwd().toString().equals(loginpwd.getText().toString()))
{
Toast.makeText(getApplicationContext(), "Login Successfull. Welcome " + login.getUname().toUpperCase() +" !".toString(),
Toast.LENGTH_LONG).show();
}
else if(login.getUname().toString().equals(loginuname.getText().toString()) &&
!login.getPwd().toString().equals(loginpwd.getText().toString()))
{
Toast.makeText(getApplicationContext(), "Login Failed. Incorrect password !",
Toast.LENGTH_LONG).show();
}
else
Toast.makeText(getApplicationContext(), "Login Failed. User doesn't exist !",
Toast.LENGTH_LONG).show(); //it never goes here if no username is found in the table
SUSQLiteHelper.java
public LoginData readOneUser(String uname, String pwd)
{
SQLiteDatabase loginUserDB = this.getReadableDatabase();
LoginData newLogin = null;
Cursor cursor = loginUserDB.query(TABLE_NAME, new String[]{TABLE_ROW_UNAME, TABLE_ROW_EMAIL, TABLE_ROW_PWD}, TABLE_ROW_UNAME + "=?",
new String[]{String.valueOf(uname)}, null, null, null);
if(cursor.moveToFirst())
{
newLogin = new LoginData(cursor.getString(0), cursor.getString(1), cursor.getString(2));
}
cursor.close();
loginUserDB.close();
return newLogin;
}
LoginData.java
此类具有Uname,Pwd,Email字段的getter和setter方法以及将这些字段作为参数的构造函数。
答案 0 :(得分:0)
在函数readOneUser()中,检查:
if(cursor.moveToFirst() && !cursor.isAfterLast()) {
//
}
答案 1 :(得分:0)
CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
这意味着cursor.moveToFirst() returns false
和Cursor is empty
。因此,尝试添加片段以检查游标是否为空,并依赖于修改逻辑。
public LoginData readOneUser(String uname, String pwd)
{
SQLiteDatabase loginUserDB = this.getReadableDatabase();
LoginData newLogin = null;
Cursor cursor = loginUserDB.query(TABLE_NAME, new String[]{TABLE_ROW_UNAME, TABLE_ROW_EMAIL,TABLE_ROW_PWD}, TABLE_ROW_UNAME + "=?",new String[]{String.valueOf(uname)}, null, null, null);
if(cursor!=null) //Check whether cursor is null or not
{
if(cursor.moveToFirst())
{
newLogin = new LoginData(cursor.getString(0), cursor.getString(1), cursor.getString(2));
}
}
cursor.close();
loginUserDB.close();
return newLogin;
}
LoginData login = dbhelper.readOneUser(loginuname.getText().toString(), loginpwd.getText().toString());
if(login!=null)
{
//check for incorrect username or password
}
else
{
//Notify that no Username available with these Username
}