KaliMa
KaliMa

Reputation: 2060

Using Singleton pattern for Sqlite database in Android

I am a little confused how to do this properly. Here is my DatabaseHelper class:

public class DatabaseHelper extends SQLiteOpenHelper {
    private static DatabaseHelper mInstance = null;

    private static final String DB_NAME = "database.db";
    private static final int DB_VERSION = 1; 

    private Context mContext;

    public static DatabaseHelper getInstance(Context context) {

        if (mInstance == null) {
            mInstance = new DatabaseHelper(context.getApplicationContext());
        }
        return mInstance;
    }

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        mContext = context;
    }

  ...

Assuming this is right, is this the correct way to handle the querying class:

public class DatabaseProcessor {

    private SQLiteDatabase mDatabase;
    private DatabaseHelper mSQLHelper;
    private Context mContext;

    public DatabaseProcessor(Context context) {
        mContext = context;
        mSQLHelper = new DatabaseHelper(mContext);
    }

    private void open() throws SQLException {
        mDatabase = mSQLHelper.getWritableDatabase();
    }

    private void close() {
        mDatabase.close();
    }

    public void insertSomethingIntoDb(String key) {
        ContentValues values = new ContentValues();
        values.put("some_column_name", name);
        open();
        mDatabase.insert("some_table_name", null, values);
        close();
    }
...

And if this is right, how do I properly invoke a db method from somewhere else in the code such as an Activity, Fragment, etc, anywhere.

Upvotes: 1

Views: 5791

Answers (1)

Titus
Titus

Reputation: 22474

You should make the DatabaseHelper constructor private and create instances of this class by using the getInstance method. eg: mSQLHelper = DatamabseHelper.getInstance(context).

To call a method of this class, you can do something like this.

DatabaseHelper.getInstance(context).someFunction(...);

And to use any of the DatabaseProcessor functions, you can do this:

new DatabaseProcessor(context).insertSomethingIntoDb(...);

Keep in mind that this singleton approach has some problems, for starters, it doesn't support multithreading, there is no mechanism in place to assure that if two threads ask for an instance at the same time, only one instance will be created.

Upvotes: 4

Related Questions