Wednesday, January 25, 2012

Android SQLite database performance improvement for inserting rows.

I was trying to insert 2000 rows into a SQLite table and following code took almost 30s in emulator and few minuets on device which of course varies.
/* db helper class */
public void insert(ContentValues cv) throws RuntimeException{
    db.insert("my_table", null, cv);
}


/* activity class*/
while(for each rows)
  insert(data);
After handling the transaction manually for all the rows at a time the performance improved drastically and here is the code.
public void insert(List dataArr) throws RuntimeException{
    db.beginTransaction();
    for(int i=0, j=dataArr.size(); i<j; i++) {
        ContentValues cv = (ContentValues)dataArr.get(i);
        db.insert("my_table", null, cv);
    }
    db.setTransactionSuccessful();
    db.endTransaction();
}

No comments: