Yosi199
Yosi199

Reputation: 1804

Design - Where to open, insert and close DB from?

I need some design suggestions.

Here is my user story:

As a user, I want to save my working hours into DB for later reviewing. I want it to be simple, from main screen with a click of a button.

The way I handle this in my app is that from my main application fragment, when a user clicks on a button it will call on a factory class that will instantiate the right class (lets call - class "X") for this type of work, and return it to the main fragment to interact with.

In class "X" constructor I establish and open the DB connection and in one of this class methods I insert new data into the DB.

My question is - is this a good design? Will I have memory leaks? Is there something I need to consider?

I've attached a UML like flow of classes for help:

 +-----------------+                 +----------------------+
 |MainFragment     |                 |      Factory         |
 |-----------------|                 |----------------------|
 |                 |                 | ChooseShiftObject    |
 |                 |+---------+----+ |                      |
 | CheckIn()       |                 |                      |
 +-----------------+                 |                      |
                                     +----------------------+
                                              +
                                              |
                                              |
                                              +
                                              |
                                         +    +
                                    +-----------------------+
                                    |       Shift           |
                                    |-----------------------|
                                    |   DB.Open()           |
                                    |   DB.Insert(bla, bla. bla)
                                    |   DB.Close()          |
                                    |                       |
                                    |                       |
                                    |                       |
                                    +-----------------------+

Upvotes: 1

Views: 81

Answers (1)

Vladimir Mironov
Vladimir Mironov

Reputation: 30874

There is one thing you should know about databases in android. You have to create your SQLiteOpenHelper object as a singleton, otherwise you will get into problems in a multithreaded environment. You can find an explanation here and here why you have to do it.

Upvotes: 1

Related Questions