3

In my application one service is getting data from server and inserting it to table A.

If I go to particular UI, I need to list data from another table B if background operation is doing it will generate database locked exception. I got two database operation done in parallel each on two different table.

It is working fine in samsung gt15801. But htc desire it will generate database locked error.

HTC desire - insertion process takes 91 seconds.

Samsung gt15801 - insertion process takes 21 seconds.

Charles
  • 50,943
  • 13
  • 104
  • 142
Dev.Sinto
  • 6,802
  • 8
  • 36
  • 54
  • Using [this](http://notes.theorbis.net/2010/02/batch-insert-to-sqlite-on-android.html) method takes less time for insertion now it takes only 3 seconds instead of 91 seconds – Dev.Sinto Aug 06 '11 at 08:06

1 Answers1

14

Try to use one SqliteDatabaseHelper and make it single instance. After that don't close the SqliteDatabase instance after complete your operations.

You can implement lock on database for that see this

http://www.sqlite.org/lockingv3.html

When you start a database operation which has many concurrent operation then you have to use

database.beginTransaction(); /* for start transaction */

and after completing operation on database you can use

database.setTransactionSuccessful();    
database.endTransaction();

But if you give error in between transaction then don't set database.setTransactionSuccessful(); so that the transaction will be rollback.

Also you can check at the time of error whether currently the database is in transaction or not by database.inTransaction(); if it return true then you are in transaction else you are not in transaction

Also You can check for whether current database has locked or not by calling

database.isDbLockedByCurrentThread();
database.isDbLockedByOtherThreads();

this will return Boolean.

Also you can set whether you want to lock your database if multiple threads are trying to read and write your database at the same time by

database.setLockingEnabled(boolean);

Above deleted methods are deprecated so please do not use.

Dharmendra
  • 33,296
  • 22
  • 86
  • 129
  • thanks for the reply.so if I want to do concurrent operation on database then I need to do LOCK right? thanks. – Dev.Sinto Aug 05 '11 at 12:02
  • 1
    do not use `isDbLockedByOtherThreads()` as it will always return false. There is no longer concept of database lock.http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#isDbLockedByOtherThreads() – Muhammad Babar Oct 21 '14 at 09:25