Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to call getWritableDatabase() everytime I manipulate data

Tags:

android

sqlite

I have a newbie question about sqlite databases in android:

Do I really need to retrieve a writeable database everytime I manipulate data?

So can I write a DAO like this:

class Dao {

        private final SQLiteDatabase database;

        public Dao(SQLiteOpenHelper databaseHelper){

             database = databaseHelper.getWritableDatabase();
    }

    public void insert(...){

       ContentValues cv = new ContentValues(4);
       database.insertOrThrow(TABLE, null, cv);
       ...
    }


    public void update(...){
        ContentValues cv = new ContentValues(4);
        database.update(....);
    }
}

or do I must write my dao like this:

class Dao {

        private final SQLiteOpenHelper databaseHelper;

        public Dao(SQLiteOpenHelper databaseHelper){

             this.databaseHelper = databaseHelper
    }

    public void insert(...){

       SQLiteDatabase database = databaseHelper.getWritableDatabase();
       ContentValues cv = new ContentValues(4);
       database.insertOrThrow(TABLE, null, cv);
       ...
    }


    public void update(...){
        SQLiteDatabase database = databaseHelper.getWritableDatabase();
        ContentValues cv = new ContentValues(4);
        database.update(....);
    }
}

If the second approach is the correct one: do I also need to close the database after every operation:

public void update(...){
    SQLiteDatabase database = databaseHelper.getWritableDatabase();
    ContentValues cv = new ContentValues(4);
    database.update(....);
    database.close();
}

I guess its the same for databaseHelper.getReadableDatabase() right?

like image 889
sockeqwe Avatar asked Sep 03 '13 14:09

sockeqwe


1 Answers

You should close every cursor you open. But the database instance doesn't need to be closed after each use.

I usually fetch a writable database in onCreate() and store the resulting SQLiteDatabase as a member variable for each activity, and never explicitly close that instance. (But again, I do close every cursor as soon as I'm finished processing their results.)

See Managing SQLite Connections in Android for a little more discussion on the subject.

like image 180
Jon Adams Avatar answered Nov 15 '22 18:11

Jon Adams