accessing db using greendao across application

301 Views Asked by At

I've started learning and using greendao ORM and I have this issue. I'm writing a memo / alert application and this means I need access to the DB from various activities and also services and receivers. For example: on one screen I'm setting the alerts' values. On a service and a receiver I'm reading those values and act accordingly.

the setup and DB access with objects and relations seem to be working fine from inside my main activity oncreate() as i've just setup the coder there to test and debug.

I thought of writing a singleton class that will handle all DB access and operations, but as it's not an activity it has no "context" I am aware that passing context as a parameter is a bad idea. I need to find a way to have DB access from all of the above mentioned.

Also, I've read somewhere that I should not initialise the DB in the main activity. Can someone elaborate on that and explain the idea of initialization and the problem with the main activity?

Hope I was able to clear my issues. Thanks for reading and possibly answering.

1

There are 1 best solutions below

0
On

Leaking a Context means you've kept a reference to a Context beyond its normal lifecycle--usually an Activity that has been finished or a Service that has been stopped. Passing a Context as a method argument does not mean there is a leak. It's only a leak if you save a reference to that Context in a field and keep it beyond the point that the system wants to destroy it (so your reference prevents it from being garbage collected). The same can happen if you keep a reference to something else that keeps a reference to a Context, the prime example of which is a View.

There is an application Context that lives as long as your application process does, and is always a singleton. Holding a reference to it is not a leak. This means you can use it in your singleton database helper class without worrying it will leak. Your singleton can actually accept any Context because you can simply call .getApplicationContext() on it to get this application context instance.

Subclassing Application is optional. In my opinion, the benefit of doing so is using the application's onCreate() method to do any one-time setup since this is your first opportunity to run application code.

Here is a great article on Contexts that might be useful: https://possiblemobile.com/2013/06/context/