SQLite:首次运行时光标出错

时间:2014-01-02 19:02:15

标签: android sql sqlite

我的程序每次运行时都能正常工作,除了第一个,在这段代码的最后一行转储:

public static SQLiteDatabase db;
private String[] niveles = new String [8];
static int nivelesSuperados = 1, col = 999;
public static Cursor c;
BDhelper dbhelper = new BDhelper(this, "BaseDatos", null, 1); 
db = dbhelper.getWritableDatabase();
c = db.rawQuery("SELECT nivel FROM Tabla", null);
if (c.moveToLast()==false) { //if there aren't rows to get
    ContentValues nuevoNivel = new ContentValues();
    nuevoNivel.put("nivel", "nivel1");
    db.insert("Tabla", null, nuevoNivel);
    c.moveToLast();
}
col = c.getColumnIndex("nivel");
niveles[0] = c.getString(col);

看起来很容易,但我找不到解决方案

1 个答案:

答案 0 :(得分:2)

将数据插入数据库时​​,它不会影响您已拥有的查询,即Cursor。您将不得不再次查询数据库以获取包含所需数据的新Cursor。但是考虑到你只是放置了数据,在读取数据库中找到你已经知道的值并没有任何意义。

所以,改变

c = db.rawQuery("SELECT nivel FROM Tabla", null);
if (c.moveToLast()==false) { //if there aren't rows to get
    ContentValues nuevoNivel = new ContentValues();
    nuevoNivel.put("nivel", "nivel1");
    db.insert("Tabla", null, nuevoNivel);
    c.moveToLast();
}
col = c.getColumnIndex("nivel");
niveles[0] = c.getString(col);

类似

c = db.rawQuery("SELECT nivel FROM Tabla", null);
if (c.moveToLast()==false) { //if there aren't rows to get
    ContentValues nuevoNivel = new ContentValues();
    nuevoNivel.put("nivel", "nivel1");
    db.insert("Tabla", null, nuevoNivel);
    niveles[0] = "nivel1";
} else {
    col = c.getColumnIndex("nivel");
    niveles[0] = c.getString(col);
}