Android - Using Dao Pattern with contentProvider
Asked Answered
M

1

15

Is correct to use ContentProvider with dao Pattern. ? or it will bring any performance issue ?

I will try to explain. I've a contentProvider. an activity, a dao and a bean ..

this is the code :

class Bean(){

 String name;

}

class Dao{

 Activity activity;

 public Dao(Activity activity){

 this.activity = activity;

public List<Bean> getAllBean() {

    Cursor c = activity.managedQuery(Bean.CONTENT_URI, PROJECTION,
                null, null, Bean.DEFAULT_SORT_ORDER);
    return BeanMapper.GetAllFromCursor(c);
    }
}

}

Class Activity{
.....


 onCreate(....){

  Dao dao = new Dao(this);
  List<Bean> aList = dao.getAllBean();

}
....}

what do you think ?

regards

Mallard answered 15/2, 2011 at 18:59 Comment(0)
C
35

DAO is designed to provide an abstract interface to a database. ContentProvider already does this.

Yes, you can make a second abstraction layer to provide a DAO API, but... You're programming on a mobile device. Using the ContentProvider API directly is going to be more efficient. There are many examples of this. For example, look at how closely Cursors and ListViews are coupled -- Look at the CursorAdapter classes and you'll see how it's designed to directly map from a database cursor to a list on the screen. Look at ContentObserver, and see how that's designed to push-notify a cursor to update to match a changed database, and in turn, update a single list element in a ListView to reflect that database as it changes in realtime...

You're going to spend immense effort reinventing the wheel trying to get all that existing code to carry through a DAO model. I don't know your application, but I'm not sure I see the advantage you gain from it.

Chiba answered 8/3, 2011 at 16:1 Comment(1)
I think this depends on how complex your app is. For more complex apps with a lot of models and db tables, I would recommend an additional DAO api layer (For each model) that works with the content provider. Otherwise, you either end up with a content provider that only gets you partially there (in terms of a DAO) or you end up with a massive content provider with a lot of extra logic that bloats it to 1000's of lines of code. I use the DAO api layer to basically enable me to always just make a CRUD like method for each of my methods that I just need to pass the model to.Coachman

© 2022 - 2024 — McMap. All rights reserved.