android – getWritableDatabase() VS getReadableDatabase()-ThrowExceptions

Exception or error:

I am creating a database helper class and for some of the methods within it I am only querying the database and others I am writing to it.

My understanding is both these methods will open the database up and let the program either just read or write to the database.

For the query statements is it worth just using getReadableDatabase() or is there very little difference in performance between the two methods.

Thanks for your time.

How to solve:

They return the same object unless the disk is full or there is some permission error that forces to open the database in read-only mode. The name is a bit confusing though 🙂

As a rule of thumb you should put any call to these methods outside the UI thread. Both can take a long time to return.

If you are not going to write the database just use getReadableDatabase as it will contribute to your code clarity and intention.

More info here.

###

If you look at NotepadProvider.java in Google’s NotePad sample project , you will see that they use both – depending on the use-case.

###

If you are doing too many operations on database like querying, updating frequently in some random order, then it doesn’t really make any sense in using getReadabledatabase as it can be used only to read the values.

Based on your app requirement you can judge the usage. If you are only reading the values constantly then you can go for getreadabledatabase.

Note: Some times when you are trying to open data base for writable, using getwritabledatabase and if system finds an exception like write permission or so, in that case system may throw an exception. In such cases you can open the database using getreadabledatabase.

###

If you are getting ‘Database is locked’ type errors when implementing concurrent (multi-thread) db calls, use getWritableDatabase instead of getReadableDatabase.

###

Opening a database read-only should slightly improve performance, as the locking overhead will be lower.

Leave a Reply

Your email address will not be published. Required fields are marked *