Android数据库和游标

时间:2014-02-11 15:23:32

标签: java android sql sqlite

我正在尝试创建一个从表中检索数据的方法,但我遇到了 Cursor 的问题:

public ArrayList<Contenu> getTest(){

    ArrayList<Contenu> test = new ArrayList<Contenu>();

    String query = new String( "select valeur from table_contenu" );
    Cursor c = bdd.rawQuery( query , null);
    c.moveToFirst();
    while (c.moveToNext())
    {
        Contenu contenu = new Contenu();
        contenu.setValeur(c.getString(c.getPosition ())); // bug
        test.add(contenu);
    }

    return test;

日志猫:

java.lang.IllegalStateException: Couldn't read row 1, col 1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.

2 个答案:

答案 0 :(得分:2)

见:

contenu.setValeur(c.getString(c.getPosition ())); // bug

应该是:

contenu.setValeur(c.getString(c.getColumnIndex("valeur"))); // NO MORE BUG

答案 1 :(得分:2)

考虑到Artoo Detoo的回答你也应该做以下事情

改变这个:

c.moveToFirst();
while (c.moveToNext())
{
 ...
}

为此:

if(c != null)
{
    c.moveToFirst();
    do
    {
        Contenu contenu = new Contenu();
        contenu.setValeur(c.getString(c.getColumnIndex("valeur")));
        test.add(contenu);
    }while(c.moveToNext());
    c.close();
}

如果没有,你将跳过第一行。