I use reading and writing to the database without any problems . But I can not find out the difference. I searched on Internet but it 's not quite clear. Can anyone tell me the difference? In which case should I use getWritableDatabase()
or getReadableDatabase()
?
Taken from my deleted answer here (this question is a duplicate of that one).
In normal situations,
getReadableDatabase()
will return the same writable database returned bygetWritableDatabase()
.However, should it not be possible to return a writable database,
getWritableDatabase()
will fail, whereasgetReadableDatabase()
will attempt to return aREAD_ONLY
database.
Check the Reference
Since: API Level 1
Create and/or open a database. This will be the same object returned by getWritableDatabase() unless some problem, such as a full disk, requires the database to be opened read-only. In that case, a read-only database object will be returned. If the problem is fixed, a future call to getWritableDatabase() may succeed, in which case the read-only database object will be closed and the read/write object will be returned in the future.
Like getWritableDatabase(), this method may take a long time to return, so you should not call it from the application main thread, including from ContentProvider.onCreate(). Returns
a database object valid until getWritableDatabase() or close() is called.
Throws SQLiteException if the database cannot be opened
Since: API Level 1
Create and/or open a database that will be used for reading and writing. The first time this is called, the database will be opened and onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and/or onOpen(SQLiteDatabase) will be called.
Once opened successfully, the database is cached, so you can call this method every time you need to write to the database. (Make sure to call close() when you no longer need the database.) Errors such as bad permissions or a full disk may cause this method to fail, but future attempts may succeed if the problem is fixed.
Database upgrade may take a long time, you should not call this method from the application main thread, including from ContentProvider.onCreate(). Returns
a read/write database object valid until close() is called
Throws SQLiteException if the database cannot be opened for writing
The different between two is the condition when disk become full. Both the getReadableDatabase()
and getWritableDatabase()
task is to open/create database.
But when the disk got full application crashes if you make a call to getWritableDatabase()
. However, getReadbleDatabase()
works fine in this case. Since, the getReadableDatabase()
blocks write operations and allows Read operation.
Don't call these methods from applications main thread like from onCreate()
method of MainActivity
in Android or any callback methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With