0

I currently use the following pattern when accessing my SQLite database (possibly from different threads):

try(SQLiteDatabase db = new MySqliteOpenHelper(context).getWritableDatabase()) {
    ...
}

Until now I thought that it was clean and thread-safe, but I got some crashes due to "Database is locked".

Why is this pattern wrong and how should I change it?

3
  • what's MySqliteOpenHelper ? Which part do you think is thread safe? Commented Jan 27, 2017 at 16:54
  • @Blackbelt the SQLiteOpenHelper part Commented Jan 27, 2017 at 17:00
  • @Blackbelt Or the SQLiteDatabase part maybe Commented Jan 27, 2017 at 17:05

1 Answer 1

1

MySqliteOpenHelper is not a singleton. To create a singleton in that class do the following in MySqliteOpenHelper.

1 Add a static instance variable of type MySqliteOpenHelper

2 Add a method called getInstance(Context) (body as shown below)

public synchronized static getInstance(Context context){
    if(instance == null){
        instance = new MySqliteOpenHelper(context);
    }
    return instance;
}

This is thread safe as you will always be using one object.

Sign up to request clarification or add additional context in comments.

10 Comments

But I've read that SQLiteOpenHelper is supposed to handle thread safety, isn't it?
I've never read anything similar, do you have a source?
stackoverflow.com/a/6675272/569558 : "You shoud use locking-related SQLiteHelper methods to provide thread safety."
That's saying SQLiteDatabase is thread safe not SQLiteOpenHelper
You're right, but then why do I need to handle thread-safety myself if SQLiteDatabase handles it?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.