本文介绍了Android的SQLite的CursorIndexOutOfBounds的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
出于某种原因,在未找到用户名I输入,应用程序崩溃。但是,当用户名发现它似乎完美运行。我甚至做了检查,如果返回的指针== null来看看。继承人的code
公共布尔isUserAuthenticated(字符串用户名,字符串密码){
// TODO自动生成方法存根
布尔认证= FALSE;
的String []列=新的String [] {LOGIN_USERNAME,LOGIN_PASSWORD};
字符串sqlUsername =\+用户名+\;
光标C = ourDatabase.query(LOGIN_TABLE,列,LOGIN_USERNAME +=+ sqlUsername,NULL,NULL,NULL,NULL);
如果(C!= NULL){
c.moveToFirst();
串passwordAttachedToUsername = c.getString(1);
如果(passwordAttachedToUsername.equals(密码)){
认证= TRUE;
}
}
返回认证;
}
解决方案
您Cursor对象不能为null,但它的结果集的大小为0而不是:
如果(C!= NULL){
...
}
尝试:
如果(c.getCount()0){
...
}
此外,作为@mu太短提到的,你可以只使用c.moveToFirst()的返回值在有条件的:
如果(c.moveToFirst()){
串passwordAttachedToUsername = c.getString(1);
如果(passwordAttachedToUsername.equals(密码)){
认证= TRUE;
}
}
For some reason when the username I input is not found, the application crashes. But when the username is found it seems to run perfect. I even do a check to see if the returned cursor == null. Heres the code
public boolean isUserAuthenticated(String username, String password) {
// TODO Auto-generated method stub
boolean authenticated = false;
String[] columns = new String[] {LOGIN_USERNAME, LOGIN_PASSWORD};
String sqlUsername = "\"" + username + "\"";
Cursor c = ourDatabase.query(LOGIN_TABLE, columns, LOGIN_USERNAME + "="+ sqlUsername, null, null, null, null);
if (c != null) {
c.moveToFirst();
String passwordAttachedToUsername = c.getString(1);
if(passwordAttachedToUsername.equals(password)) {
authenticated = true;
}
}
return authenticated;
}
解决方案
Your Cursor object may not be null, but the size of its result set is 0. Instead of:
if (c != null) {
...
}
try:
if (c.getCount() > 0) {
...
}
Also, as @mu is too short mentioned, you could just use the return value of c.moveToFirst() in your conditional:
if (c.moveToFirst()) {
String passwordAttachedToUsername = c.getString(1);
if (passwordAttachedToUsername.equals(password)) {
authenticated = true;
}
}
这篇关于Android的SQLite的CursorIndexOutOfBounds的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!