getWritableDatabase() VS getReadableDatabase()

16,087

Solution 1

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.

Solution 2

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

Solution 3

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.

Share:
16,087
James Dudley
Author by

James Dudley

Starting out Learning JAVA and now progressed to Android Aim to create an Archery Scorepad for the Android

Updated on June 14, 2022

Comments

  • James Dudley
    James Dudley almost 2 years

    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.

  • mgv
    mgv almost 13 years
    This isn't really true. The call to getReadableDatabase will return a writable database object most of the time, unless the disk is full or there are permission errors.
  • James Dudley
    James Dudley almost 13 years
    So basically there is no different in performance and usage between either method. thanks
  • user2864740
    user2864740 over 10 years
    @JamesDudley Except that getReadableDatabase doesn't have to return a writable database.
  • Sourav Kanta
    Sourav Kanta almost 8 years
    So can I execute select statements even if i use getWritableDataBase?