0

I'm trying to put all the DatabaseRequests inside a module in Android to centralize all the acces to DDBB in the same place.

I'm wondering if I'm making any mistake doing that. The apps works in the right way but I'm concerned about best practices doing that.

I have an static class called DatabaseRequest where all the requests are inside, for instance:

public static void insertUser(Context context, User user) {
    DataBaseHelper mDataBaseHelper = OpenHelperManager.getHelper(context, DataBaseHelper.class);

    try {
        Dao<User, Integer> dao = mDataBaseHelper.getUserDao();
        dao.createOrUpdate(user);

    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (mDataBaseHelper != null) {
            OpenHelperManager.releaseHelper();
        }
    }
}

The context param is the context of the activity that's making the request.

Is there any performance issue related with this code?

Thanks in advance ;)

MarcForn
  • 3,321
  • 7
  • 25
  • 39

1 Answers1

0

No, as Gray (ORMlite creator) said in this post:

is it ok to create ORMLite database helper in Application class?

What is most important with your code is that it guarantees a single databaseHelper instance. Each instance has it's own connection to the database and problems happen when there are more than one (1) connection opened to the database in a program. Sqlite handles multiple threads using the same connection at the same time but it doesn't handle multiple connections well and data inconsistencies may occur.

And in your case you may have multiple connections at one time.

I can preset you my approach on how I'm using ORMlite, I have one singleton class public class DbHelper extends OrmLiteSqliteOpenHelper which takes care of creating database connection and holds all Dao fields. You will have database upgrade code there and some other stuff so consider making facade classes. In my case each facade holds one Dao object for one model class, where i keep logic for complex item retrieving (and for simple cases i just delegate it to Dao object.

Community
  • 1
  • 1
Than
  • 2,759
  • 1
  • 20
  • 41
  • According to Gray, will you find more appropiate to put all the logic inside the application class, as the post explains? – MarcForn Nov 07 '15 at 12:55
  • Do you ever explicitly release your DBHelper, @Than? Or do you just create a `Singleton` that's hooked into the `Application` lifecycle. – Sakiboy Jun 26 '17 at 07:39