aztek
aztek

Reputation: 93

When should I build the room database instance?

First time posting a question and I'm a coding noob so sorry if I do something wrong.

I check around and found one answer which is somewhat similar to my question: When / How to Create / Destroy Room Database

However I am not using dagger, nor do I know how to use it.

I wanted to ask when should you build your room database instance? Suppose my app uses the database throughout, should I build it in the OnCreate of the Main Activity? Or should I only build it once the users tries to access some functionality that requires it?

This is the code in question:

instance = Room.databaseBuilder(context.getApplicationContext(), MovieDatabase.class, DB_NAME).build();

So basically when is the best time to run the above code?

Please let me know if this question doesn't make sense.

Upvotes: 3

Views: 1312

Answers (3)

user12709908
user12709908

Reputation:

The build itself does not open/connect the database and is therefore not resource intensive so this can be done anywhere. Probably, in general, the best place is to build in the MainActivity.

It is not until you actually try to do something with the database (insert/update/delete/query) that the open/connection is then done, which can be relatively resource intensive. Hence, why by default, Room does not allow you to do anything on the main thread (using .allowMainThreadQueries when building, can be used to override this restriction).

You can force an open/connection e.g. by getting a SupportSQLiteDatabase using. for example, theBuiltDatabase.openHelper.writableDatabase (theBuiltDatabase representing the database that has been partially built) (this can run on the main thread irresepective of allowMainThreadQueries). However, you probably don't want to do this.

Upvotes: 1

Ajeett
Ajeett

Reputation: 812

Create an Application Class where you will create a singleton object of it.You can go through this example. It explains all your requirements.

Upvotes: 1

Mohamed Nageh
Mohamed Nageh

Reputation: 2043

Your Database Instance will be built as Singleton and you can access it anywhere as it will be created only once.

Please follow this codelab tutorial to get a clear vision of using Room

Upvotes: 3

Related Questions