如何检查光标在android系统空或不是? [英] How to check cursor null or not in android?

查看:134
本文介绍了如何检查光标在android系统空或不是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查 BangCauHoi 表中的字段 ID 的值。
这是我的功能:

I'm trying to check values of field ID in BangCauHoi table. This is my function:

public boolean checkID(String ndCauHoi){
        boolean check = true;
        String query = "select ID from BangCauHoi where CauHoi=?";
        Cursor c = database.rawQuery(query, new String[] { ndCauHoi });
        if (c != null)
        {
             c.moveToFirst();
                 if (c.isNull(c.getColumnIndex("ID")))
                 {
                     check = false;
                 }
        }
         c.close();
    return check;
}

和结果是:

java.lang.RuntimeException: Unable to start activity ComponentInfo{us.datn_02/us.datn_02.ShowQuestion}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

有人能帮助我吗?

Somebody can help me please?

如果我改变我的code为:

if I change my code to:

public boolean checkID(String ndCauHoi){
        boolean check = true;
        String query = "select ID from BangCauHoi where CauHoi=?";
        Cursor c = database.rawQuery(query, new String[] { ndCauHoi });
        if (c.moveToFirst())
        {
                 if (c.isNull(c.getColumnIndex("ID")))
                 {
                     check = false;
                 }
        }
         c.close();
    return check;
}

那么它总是返回真正连场 ID 有这个没有价值,其中条款。

then it always return true even field ID have no value with this where clause.

请帮助我!...
抱歉,因为我的英语水平。

Help me please!... Sorry because my english.

推荐答案

您可以检查它是否为空,用下面的语句:

You can check to see whether or not it is empty with the following statement:

if (c.moveTofirst() && c.getCount > 0)

if (c != null && c.moveToFirst())

至于为什么是空的,我猜你是在什么地方打错了言。我总是用查询 SQLiteDatabase 类,而不是 rawQuery 方法和使用常量我列名,而不是硬编码他们尝试和避免这些问题。

As to why it is empty, I would guess that you have mistyped a statement somewhere. I always use the query method in the SQLiteDatabase class instead of rawQuery, and use constants for my column names instead of hardcoding them to try and avoid these problems.

public static final String KEY_ID = "_id";
public static final String TABLE_NAME="BangCauHoi";
public static final String CAUHOI = "CauHoi";

Cursor c = yourDatabaseInstance.getReadabledatabase().query(
    YourDatabaseName.TABLE_NAME, 
    new String[] { YourDatabaseName.KEY_ID },
    YourDatabaseName.CAUHOI + "=?", 
    new String[] { ndCauHoi }, 
    null, null, null);

这篇关于如何检查光标在android系统空或不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆