SQLite on Android doesn't insert properly -
i making android app learn sqlite databases. have function should write user's movement data accelerometer database. database created with:
db.execsql("create table if not exists data(id integer primary key autoincrement, "+ "lat integer, long integer, "+ "movement real, "+ "time text);");
and function writes db called every 2 seconds:
void inserttable(float mov) { db.begintransaction(); try { // part gets current time calendar = 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 data(movement ,time) values ("+ mov+",'"+date+"');"); cursor c1 = db.rawquery("select * data", null); // happens after 5th iteration , app crashes if(numrefreshes>5) c1.movetoposition(2); // happens first 5 iterations of function else c1.movetoposition(0); // time , date , show on screen string datum = c1.getstring(4); c1.close(); dbresult.settext(datum); // keep track of how many times function has been called numrefreshes++; } catch(sqliteexception e) { toast.maketext(getbasecontext(), e.getmessage(), toast.length_short).show(); } { db.endtransaction(); } }
as see, first 5 times function called print date 1st row in table. shows value last row inserted. that's fine, guess. after 5th time, when try read date value of 3rd row, crashes , logcat says:
fatal exception: main android.database.cursorindexoutofboundsexception: index 1 requested, size of 1
so presume sqlite overwrites previous row each time. doing wrong?
it not calling method set transaction successful.
you need add db.settransactionsuccessful()
after numrefreshes++;
if @ java doc db.begintransaction()
find
db.begintransaction(); try { ... db.settransactionsuccessful(); } { db.endtransaction(); }
without settransactionsuccessful rolling insert do
Comments
Post a Comment