如何从android中的光标中检索与特定字段对应的数据?

时间:2012-07-27 12:15:56

标签: android sqlite

数据库类

public boolean Permissions(String modulename) {
    int createable, updateable;
    Cursor cursor = db.rawQuery("select * from " + "moduleDesc" + " where "
            + "name" + "='" + modulename + "'", null);
    if (cursor.getCount() > 0);
        {
        createable = cursor.getInt(cursor.getColumnIndex("createable"));
        updateable = cursor.getInt(cursor.getColumnIndex("updateable"));
        cursor.close();
    }
    if ((createable == 1) && (updateable == 1)) {
        return true;

    } else {
        return false;
    }
}

我得到的错误是cursorindexoutofbounds on createable cursor.getInt(cursor.getColumnIndex("createable")); 虽然光标仍然有一些值仍然给出了这个错误!提前谢谢

3 个答案:

答案 0 :(得分:1)

而不是:

  if (cursor.getCount() > 0) { 
      //Code here
  }

使用

  if (cursor.moveToFirst()) { 
      //Code here
  }

这可能会解决您的问题。

答案 1 :(得分:1)

Try this solution 

public boolean Permissions(String modulename) {
int createable, updateable;
Cursor cursor = db.rawQuery("select * from " + "moduleDesc" + " where "
        + "name" + "='" + modulename + "'", null);
if (cursor.getCount() > 0);
    {
    cursor.MoveToFirst();//use this if cursor count is 1 else use while loop 
    //while (cursor.MoveToNext){
    createable = cursor.getInt(cursor.getColumnIndex("createable"));
    updateable = cursor.getInt(cursor.getColumnIndex("updateable"));
    //}
    cursor.close();
}
if ((createable == 1) && (updateable == 1)) {
    return true;

} else {
    return false;
}

}

答案 2 :(得分:0)

正确关闭光标。

public boolean Permissions(String modulename) {
    Cursor cursor = db.rawQuery("select * from " + "moduleDesc" + " where "
            + "name" + "='" + modulename + "'", null);
    if (cursor != null) {
        try {
           if (cursor.moveToFirst()) {
               int createable = cursor.getInt(cursor.getColumnIndex("createable"));
               int updateable = cursor.getInt(cursor.getColumnIndex("updateable"));
               return (createable == 1) && (updateable == 1);
           }
        } finally {
            cursor.close();
        }
    }
   return false;
}