1

我正在制作一个 Android 应用程序来学习 SQLite 数据库。我有一个函数应该将用户的运动数据从加速度计写入数据库。数据库是通过以下方式创建的:

db.execSQL("create table if not exists data(ID integer primary key autoincrement, "+
"lat integer, long integer, "+
"movement real, "+
"time text);");

写入数据库的函数每 2 秒调用一次:

void insertTable(float mov)
{

    db.beginTransaction();
    try
    {
        // this part gets the current time
        Calendar now = Calendar.getInstance();
        String date = now.get(Calendar.HOUR_OF_DAY)+":"+now.get(Calendar.MINUTE)+":"+now.get(Calendar.SECOND)+
        "."+now.get(Calendar.MILLISECOND)+" "+now.get(Calendar.DAY_OF_MONTH)+"/"+now.get(Calendar.MONTH)+
        "/"+now.get(Calendar.YEAR);


        db.execSQL("insert into data(movement ,time) values ("+
                mov+",'"+date+"');");
        Cursor c1 = db.rawQuery("select * from data", null);

                    // this happens after the 5th iteration and the app crashes
        if(numRefreshes>5) c1.moveToPosition(2);

                    // this happens the first 5 iterations of this function
        else c1.moveToPosition(0);

                    // get time and date and show it on the screen
        String datum = c1.getString(4);
        c1.close();
        dbResult.setText(datum);

                    // keep track of how many times this function has been called
        numRefreshes++;
    }
    catch(SQLiteException e)
    {
        Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
    }
    finally
    {
        db.endTransaction();
    }
}

如您所见,调用此函数的前 5 次它将打印表中第一行的日期。它始终显示插入的最后一行的值。没关系,我猜。但是在第五次之后,当我尝试读取第三行的日期值时,它崩溃了,LogCat 说:

FATAL EXCEPTION: main
android.database.CursorIndexOutOfBoundsException: Index 1 requested, with a size of 1

所以我假设 SQLite 每次都会覆盖我的前一行。我究竟做错了什么?

4

1 回答 1

3

看起来您没有调用将事务设置为成功的方法。

您需要在db.setTransactionSuccessful()之后添加numRefreshes++;

如果您查看 java 文档,db.beginTransaction()您会发现

db.beginTransaction();
try {
 ...
  db.setTransactionSuccessful();
} finally {
 db.endTransaction();
}

如果没有 setTransactionSuccessful,您将回滚您所做的任何插入

于 2013-07-17T23:19:10.590 回答