我正在制作一个 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 每次都会覆盖我的前一行。我究竟做错了什么?