2017-04-21 118 views
0

我在检查游标是否包含任何结果时遇到了很多麻烦。检查Cursor是否包含行结果?

我有一个方法是“删除”,从给定的表,它是在这里的所有行:

Chevron.class 
    public void deleteAllRecords(){ 
    SQLiteDatabase db = this.getWritableDatabase(); 
    db.delete(TABLE_NAME,null,null); 
} 

我然后调用它增加了数据库的第一行是这里的SUM的方法:

public Cursor getRecalculate(){ 
    SQLiteDatabase db = this.getWritableDatabase(); 
    Cursor res = db.rawQuery("select SUM (" + SECOND_FIELD + ") FROM " + TABLE_NAME, null); 
     return res; 
    } 

我的主要问题是,如果我从数据库中删除所有记录,res.getCount()仍然等于1,但不包含任何信息,但随后该方法只反正返回1行。所以我坚持如何检查游标是否有实际的表数据或只是空表数据。像

if(res.getString(0) == null){ 
    .. Do code 
} 

我试过的东西不起作用。

我得到的错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ceri.twostep_onecheck/com.example.ceri.twostep_onecheck.ShowGraph}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1 
+0

' “SELECT COUNT(*),SUM(” + SECOND_FIELD +“)FROM”+ TABLE_NAME',看看'getInt(0)'是否> 0。 – CommonsWare

+0

@CommonsWare我得到相同的错误说:android.database.CursorIndexOutOfBoundsException:索引-1请求,大小为1 – user3042332

+1

你没有调用'光标''moveToFirst()'。当你得到它时,“光标”总是位于第一行之前。顺便说一下,在将问题发布到涉及崩溃的堆栈溢出时,请将*整个堆栈跟踪*,而不仅仅是一行。 – CommonsWare

回答

0

如果你想知道有多少行是您搜索条件的限制,加上COUNT(*)SELECT声明:

SELECT COUNT(*), SUM(whatever) FROM other_thing; 

然后,移动Cursor通过moveToFirst()添加到第一行,并检查两个值(计数的getInt(0)和总计的getInt(1))。

0

使用getReadableDatabase()而不是getWritableDatabase()

试试这个:

public Cursor getRecalculate() { 
    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor res = db.rawQuery("select SUM (" + SECOND_FIELD + ") FROM " + TABLE_NAME, null); 
    return res; 
} 

阅读cursor值:

// Move the cursor to the first row if cursor is not empty 
if(res.moveToFirst()) 
{ 
    do 
    { 
     // Do something with cursor 

    }while(res.moveToNext()); // Move cursor to next row until it pass last entry 
} 

// Close 
res.close(); 

希望这将有助于〜