Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android/Java: accessing the same SQLite DB object from multiple activities

I have a central database in my application that a few different activities need to access.

Should I share this object by making it static? Like for example in the activity that initializes the DB I do this:

protected static appDatabase db;

Then others can access it via FirstActivity.db.

Another option is to create private appDatabase db objects in every activity that needs it, but I suspect opening multiple db objects to access the same stored data may be wasteful.

However I don't know too much about java which is why I'm asking - what's the preferred way to do this, and why?

Thanks

like image 349
JDS Avatar asked Jan 06 '13 19:01

JDS


1 Answers

You can use singleton like this;

    private static DataHelper singleton;

    public static DataHelper getDataHelper(Context context) {
            if (singleton == null) {
                    singleton = new DataHelper(context);
                    OpenHelper openHelper = new OpenHelper(singleton.context);
                    singleton.db = openHelper.getWritableDatabase();
            }
            if(!singleton.db.isOpen()){
                    OpenHelper openHelper = new OpenHelper(singleton.context);
                    singleton.db = openHelper.getWritableDatabase();
            }
            singleton.context = context;
            return singleton;
    }

    private DataHelper(Context context) {
        this.context = context;
}

And call your singleton class like this;

public DataHelper dh;
this.dh = DataHelper.getDataHelper(this);
like image 179
Mert Avatar answered Sep 30 '22 14:09

Mert