Android - What is the difference between getReadableDatabase() and getWritableDatabase()?

Asked

Viewed 1,007 times

3

I was able to enter information in the database using the method getReadableDatabase(). In that case shouldn’t it be wrong? Shouldn’t it be the method getWritableDatabase()?

private void savePet() {

        petDbHelper = new PetDbHelper(this);
        db = petDbHelper.getReadableDatabase();

        ContentValues values = new ContentValues();
        values.put(PetEntry.COLUMN_PET_NAME, mNameEditText.getText().toString());
        values.put(PetEntry.COLUMN_PET_BREED, mBreedEditText.getText().toString());
        values.put(PetEntry.COLUMN_PET_WEIGHT, mWeightEditText.getText().toString());
        values.put(PetEntry.COLUMN_PET_GENDER, mGender);

        long newRowID =
                db.insert(PetEntry.TABLE_NAME, null, values);

        /** Display rowID after finish */
        Toast.makeText(this, "New row added: " + newRowID, Toast.LENGTH_SHORT).show();

        /** Close Activity */
        finish();
    }

1 answer

4


According to the documentation, the getReadableDatabase():

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

Translating:

Creates or opens a database. This will be the same object returned for getWritableDatabase(), unless a problem occurs, such as for example: if the disk is full the database is opened in the read-only mode.

But looking at the documentation of getWritableDatabase(), it says that if the disk is full, this method will return an error.

In short: Both return the same object, so there is no error. But you should use the getWritableDatabase() to save data to better handle errors that may arise.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.