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
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.
Related
I have problems in designing data layer for android applications. More precisely I don't understand what query-like functions should return. I had such solution:
public class NotesDatabase {
// ...
public Cursor queryAllNotes() {
return helper.getReadableDatabase().query(...);
}
}
There's problem in this approach. To use result you must know query: columns and their types. It's violation of encapsulation. Also this approach creates problems for unit testing.
But I saw another approach:
public class NotesDatabase {
// ...
public List<Note> queryAllNotes() {
Cursor c = helper.getReadableDatabase().query(...);
ArrayList<Note> notes = new ArrayList<>(c.getCount());
while (c.moveToNext()) {
notes.add(new Note(c.getInt(), c.getText() ...));
}
return notes;
}
}
At least we keep encapsulation but I see other problems here. It doesn't seem to be memory performant approach. I can't use CursorAdapter and CursorLoader, can't set autorequerying which is not actually a problem. What a problem is big results. What to do if response is too big to fit in memory? Should I prevent such situation? Should I care?
So which approach is preferable? And how to solve these issues?
As you noted, the second approach would provide a better encapsulation since the caller would be dealing with a list of familiar domain model (Note) objects instead of a database cursor. To handle the problem of large data sets, this answer may be helpful.
I have a simple database in my Android app that contains information about countries. One of the things I have to do is to populate a dropdown menu with the names of the countries.
So, I wrote some simple code like so:
public class FetchCountryAsync extends AsyncTask<String,Void,Cursor> {
private Context con;
private CountryConsumer consumer;
//----------------------------------------------------------------------------------------------
public FetchCountryAsync(Context con, CountryConsumer consumer) {
this.con = con;
this.consumer = consumer;
}
//----------------------------------------------------------------------------------------------
#Override
protected Cursor doInBackground(String... params) {
CountryDatabaseHelper helper = new CountryDatabaseHelper(con);
Cursor countries = helper.getCountries();
return countries;
}
//----------------------------------------------------------------------------------------------
#Override
public void onPostExecute(Cursor countries){
if(!isCancelled()){
consumer.setCountries( countries );
}
}
//----------------------------------------------------------------------------------------------
}
There's a lot of mumbo-jumbo that I did to make it work - an AsyncTask, an interface.
My question is, would it have been a better approach to write my own ContentProvider and avoid the hassle of AsyncTask altogether?
It depends on you and what your plans are for your app.
Writing a ContentProvider would likely have been more work but it would provide a much more thorough, flexible access point to the data that you can reuse across your app. Eg query, insert, update, delete methods accessible via Uri.
ContentProviders allow you to centralize and abstract access to DB/other data in your app. This way if the db structure ever changes there's one access point to update for managing information. It just makes things cleaner in my experience. Also, if you ever decide to share the info to other apps the ContentProvider implementation will make that easy.
If its just a 1-off information retrieval task for a single activity in the app, what you have seems fine. If you'll be using it across the app and updating/inserting data in the db or doing more complex queries, it's probably worth the extra time/complexity to make a ContentProvider.
There's another good discussion related to this topic here.
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 ;)
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.
According to ORMLite documentation, all created Dao objects are cached inside DaoManager. But in ORMLite examples, I've seen Dao classes are again cached inside DatabaseHelper class. Do we really need it? ex.
public Dao<SimpleData, Integer> getDao() throws SQLException {
if (simpleDao == null) {
simpleDao = getDao(SimpleData.class);
}
return simpleDao;
}
My plan is to obtain Dao object when ever I need it and not to cache it inside my code base(In DatabaseHelper class), just want to allow DaoManager to cache Dao.
This is what I'm planing to use
DatabaseHelper databaseHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class);
Dao<SimpleData, Integer> myDao = databaseHelper.get.getDao(SimpleData.class);
Any performance issue if I obtain dao like this, instead of caching it inside DatabaseHelper?
Any performance issue if I obtain dao like this, instead of caching it inside DatabaseHelper?
No this is certainly fine. You are doing a Hashmap.get(..) call each time but that is a very small hit -- especially when compared to any DAO operations or IO.
I would recommend not doing one of these for every call to the DAO:
databaseHelper.getDao(SimpleData.class).create(...);
databaseHelper.getDao(SimpleData.class).update(...);
But if you want to just get it at the start of the method and then perform a couple of operations then this should perform fine.
So I have a custom subclass of OrmLiteSqliteOpenHelper. I want to use the ObjectCache interface to make sure I have identity-mapping from DB rows to in-memory objects, so I override getDao(...) as:
#Override
public <D extends Dao<T, ?>, T> D getDao(Class<T> arg0) throws SQLException {
D dao = super.getDao(arg0);
if (dao.getObjectCache() == null && !UNCACHED_CLASSES.contains(arg0))
dao.setObjectCache(InsightOpenHelperManager.sharedCache());
return dao;
}
My understanding is that super.getDao(Class<T> clazz) is basically doing a call to DaoManager.createDao(this.getConnectionSource(),clazz) behind the scenes, which should find a cached DAO if one exists. However...
final DatabaseHelper helpy = CustomOpenHelperManager.getHelper(StoreDatabaseHelper.class);
final CoreDao<Store, Integer> storeDao = helpy.getDao(Store.class);
DaoManager.registerDao(helpy.getConnectionSource(), storeDao);
final Dao<Store,Integer> testDao = DaoManager.createDao(helpy.getConnectionSource(), Store.class);
I would expect that (even w/o the registerDao(...) call) storeDao and testDao should be references to the same object. I see this in the Eclipse debugger, however:
Also, testDao's object cache is null.
Am I doing something wrong here? Is this a bug?
I do have a custom helper manager, but only because I needed to manage several databases. It's just a hashmap of Class<? extends DatabaseHelper> keys to instances.
The reason I need my DAO cached is that I have several foreign collections that are eager and are being loaded by internally-generated DAOs that are not using my global cache and thus are being re-created independently for each collection.
As I was writing this up, I thought I could just have my overridden helpy.getDao(...) call through to DaoManager.createDao(...), but that results in the same thing: I still get a different DAO on the second call to createDao(...). This seems to me to be totally against the docs for DaoManager.
First, I thought it looked like registerDao(...) may be the culprit:
public static synchronized void registerDao(ConnectionSource connectionSource, Dao<?, ?> dao) {
if (connectionSource == null) {
throw new IllegalArgumentException("connectionSource argument cannot be null");
}
if (dao instanceof BaseDaoImpl) {
DatabaseTableConfig<?> tableConfig = ((BaseDaoImpl<?, ?>) dao).getTableConfig();
if (tableConfig != null) {
tableMap.put(new TableConfigConnectionSource(connectionSource, tableConfig), dao);
return;
}
}
classMap.put(new ClassConnectionSource(connectionSource, dao.getDataClass()), dao);
}
That return on line 230 of the source for DaoManager prevents the classMap from being updated (since I'm using the pregenerated config files?). When my code hits the second create call, it looks at the classMap first, and somehow (against my better understanding) finds a different copy of the DAO living there. Which is super weird, because stepping through the first create, I watched the classMap be initialized.
But where would a second DAO possibly come from?
Looking forward to Gray's insight! :-)
As #Ben mentioned, there is some internal DAO creation which is screwing things up but I think he may have uncovered a bug.
Under Android, ORMLite tries to use some magic reflection to build the DAOs given the horrible reflection performance under all but the most recent Android OS versions. Whenever the user asks for the DAO for class Store (for example), the magic reflection fu is creating one DAO but internally it is using another one. I've created the follow bug:
https://sourceforge.net/tracker/?func=detail&aid=3487674&group_id=297653&atid=1255989
I changed the way the DAOs get created to do a better job of using the reflection output. The changes were pushed out in the 4.34. This release revamps (and simplifies) the internal DAO creation and caching. It should fix the issue.
http://ormlite.com/releases/
Just kidding. Looks like what may be happening is that my Store object DAO initialization is creating DAO's for foreign connections (that I set to foreignAutoRefresh) and then recursively creating another DAO for itself (since the DAO creation that started this has not completed, and thus has yet to be registered w/ the DaoManager).
Looks like this has to do w/ the recursion noted in BaseDaoImpl.initialize().
I'm getting Inception flashbacks just looking at this.