2013-07-17 64 views
1

我正在製作Android應用程序來學習SQLite數據庫。我有一個函數應該將用戶的加速度計的運動數據寫入數據庫。該數據庫與創建: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次調用這個函數會打印日期從表中的第一行開始。它始終顯示最後的行插入的值。這很好,我猜。 但5日時間後,當我嘗試讀取第三行的日期值,它崩潰和logcat的說:

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

所以我猜的SQLite覆蓋我以前每次一行。我究竟做錯了什麼?

回答

2

它看起來不像你調用的方法來設置事務成功。

你需要後numRefreshes++;

添加db.setTransactionSuccessful()如果你看一下Java文檔的db.beginTransaction()你會發現

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

沒有你將被回滾setTransactionSuccessful任何插入你做

+0

真棒!很棒。謝謝。 – kodo

+0

菜鳥的錯誤,但是因爲這是我剛纔製作的,所以我感謝你:) – TinyDancer