Viperdream
Viperdream

Reputation: 35

How can I access my SQLite Database in a static way?

I was wondering how I could access my SQLite database in my android app in a static way. I always use this when I want to access the database:

MySQLiteHelper dbHandler = new MySQLiteHelper(this, "PinDB", null, 4);

This is the constructor of MySQLiteHelper:

public MySQLiteHelper(Context context, String name, CursorFactory factory, int version){
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

Now, I have to access the database in a static way for a method I want to use. But I have no idea how I could get the context of the activity (this). I've tried ways like getApplicationContext() etc. but they all don't seem to work.

So, is it possible to change MySQLiteHelper(this,"PinDB", null, 4); into something like this? MySQLiteHelper(MyActivity, "PinDB", null, 4);

If you need any more information, please do ask!

Thanks in advance

Upvotes: 1

Views: 588

Answers (1)

elbuild
elbuild

Reputation: 4899

I use a Singleton to access the SQLite Database in Android. I think that pattern fits your use case as well.

Session.java (the Singleton class)

public class Session
{
    private static DbUtil; // static DBUtil

    protected Session() {
        //
    }

    public static Session getInstance() {
        if (instance == null) {
            instance = new Session();
        }
        return instance;
    }

    public void initDBUtil(Context ctx){
        util = new DbUtil(ctx);
    }

    public DbUtil getDbUtil()
    {
      return util;
    }

}

DbUtil.java (the class extending SQLiteOpenHelper)

public class DbUtil extends SQLiteOpenHelper
{
    public DbUtil(Context context) {
        super(context, NAME_DB, null, 1);
        // other init code here...
    }

    // onCreate and other override

}

In the first onCreate method of your entrance activity just do something like that:

Session.getInstance().initDBUtil(this);

and then you can use the getter in Session to access the DbUtil class with:

Session.getInstance().getUtil(). ... your method here ...

Upvotes: 1

Related Questions