Android,我无法从sqlite查询中获取字符串

时间:2014-01-02 12:27:20

标签: android android-sqlite

找到以下代码:

Cursor c1 = db.rawQuery("SELECT desc FROM DefectTablemain where id='defVal'", null);
c1.getString(0).toString(); // This line s breaking

if(c1 != null) { c1.moveToFirst(); String ch= c1.getColumnName(0); c1.getColumnIndex(ch); c1.getString(c1.getColumnIndex(ch)); }

在这最后一行是打破。

6 个答案:

答案 0 :(得分:2)

您没有检查光标是否为null ..它包含任何数据或不包含..这样检查..

if (c1!=null) {
        if (c1.moveToFirst()) {
            //here get the your data..
            c1.getString(0).toString();
        }
    }

答案 1 :(得分:1)

移动到光标的第一行:

 if (c1 != null)
{
    if (c1.moveToFirst())
    {
        // ...
    }
}

答案 2 :(得分:0)

在开始从光标获取数据之前,您需要将光标移到第一个位置

    Cursor c1 = db.rawQuery("SELECT desc FROM DefectTablemain where id='defVal'", null);
    c1.moveToFirst();
    c1.getString(0).toString();

答案 3 :(得分:0)

Cursor c1 = db.rawQuery("SELECT desc FROM DefectTablemain where id='defVal'", null);
if(c1!=null)  {     
 c1.moveToFirst();
        c1.getString(0).toString();

}

答案 4 :(得分:0)

public String getDesc()
{

    db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT desc FROM DefectTablemain where id='defVal' ", null);
    int count = cursor.getCount();

    String desc ="";
    if(count!=0)
    {
        while(cursor.moveToNext())
        {
            desc =cursor.getString(cursor.getColumnIndex("desc"));
        }
    }
    else
    {
        desc ="NA";
    }
    cursor.close();
    db.close();
    return desc ; 
}

答案 5 :(得分:0)

检查c1.moveToFirst()是否成功

if(c1.moveToFirst()) {
    c1.getString(0);

}

如果游标为空,Cursor.moveToFirst()将返回false。enter link description here