1

If they only perform queries on it? Something like:

private SQLiteDatabase db;

@Override
public void onCreate(Bundle savedInstanceState) {
    db = getWritableDatabse();
}

private Task1 extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... arg0) {
        db.query(doSomething);
        ...
    }
}

private Task2 extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... arg0) {
        db.query(doSomething);
        ...
    }
}
Gray
  • 115,027
  • 24
  • 293
  • 354
soren.qvist
  • 7,376
  • 14
  • 62
  • 91
  • 1
    Related to http://stackoverflow.com/questions/4498664/android-multiple-databases-open http://stackoverflow.com/questions/4234030/android-can-i-use-one-sqliteopenhelper-class-for-multiple-database-files and http://stackoverflow.com/questions/1556930/sharing-sqlite-database-between-multiple-android-activities – Gray Dec 09 '11 at 14:14

1 Answers1

8

All of your threads in your application should use the same database object -- even if reading and writing simultaneously. SQLite handles this with internal locking mechanisms appropriately.

What you don't want to do is to use multiple database objects to read and write from a database. That may result in inconsistent data.

See here:

The last link is a good one. To quote Kevin Galligan:

  • Sqlite takes care of the file level locking. Many threads can read, one can write. The locks prevent more than one writing.
  • Android implements some java locking in SQLiteDatabase to help keep things straight.
  • If you go crazy and hammer the database from many threads, your database will (or should) not be corrupted.

Here’s what’s missing. If you try to write to the database from actual distinct connections at the same time, one will fail. It will not wait till the first is done and then write. It will simply not write your change. Worse, if you don’t call the right version of insert/update on the SQLiteDatabase, you won’t get an exception. You’ll just get a message in your LogCat, and that will be it.

As an aside, Kevin has done a good bit of the work of the Android side of ORMLite, my Java ORM package that supports Android.

Community
  • 1
  • 1
Gray
  • 115,027
  • 24
  • 293
  • 354
  • Thanks, I was worried that there was going to be some sort of "collision" if two AsyncTask was trying to write at the same time, but I guess your answer clears that up. – soren.qvist Dec 09 '11 at 14:06
  • I have similar problem that I am actually reading from two or more AsyncTasks at the same time where at least two are executedOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR).. and I get following crash "java.lang.IllegalStateException: Cannot perform this operation because the connection pool has been closed.".. Guess it is related with getting readable db before every query and closing it after it so AsyncTasks overlap and one is accessing cursor in a wrong moment :S – Ewoks Jul 16 '15 at 19:56