Organizing data layer in android application - android

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.

Related

Android - Couchbase lite - DAO - MyClass extends Document

I'm working on an Android application using Couchbase lite.
Should I have my classes extending com.couchbase.lite.Document ?
Pros: DAO is integrated in class.
Cons: - every object is linked to a document, if we want a new object, we must create a new document in couchbase? - anything else?
For example:
public class UserProfile extends Document {
public UserProfile (Database database, String documentId);
public Map<String, Object> getProperties();
public boolean isModified();
public boolean update() throws CouchbaseLiteException {
if (isModified()) {
super.putProperties(getProperties());
return true;
}
else
return false;
}
}
I would not recommend extending Document. Instead, either just use Maps, or use something like the Jackson JSON library to create POJOs. I usually create a simple helper class to wrap the database operations (including replication, if you're using that).
Off the top of my head, I wouldn't do it because subclassing doesn't fit well with some of the ways you retrieve documents, documents are somewhat heavy-weight objects, and the preferred way to update takes into account the possibility of conflicts, which would be much more difficult. (See this blog post for a discussion of that last point.)
I've never tried to work around these issues in a subclassing approach, but it seems pretty certain to be more pain than it's worth.

RealmResult as RealmObject field

I'm trying to figure out the best way to set up a RealmObject with a RealmResult as one of its fields.
For example, let's say I have two RealmObjects, Goal and Achievement. The Goal object contains fields that define a query of Achievement's the user wants to track (e.g. date range the achievement was created, type of achievement, etc) and has custom methods to extract statistics from those Achievements.
What is the best way for Goal to contain this RealmResult of Achievements? Here are some ways I've thought of doing this:
Have a persisted RealmList field in Goal and update it anytime a field is changed that would change the resulting query. But how would this RealmList get updated if a new Achievement gets added to the realm?
Use #Ignore annotation on a RealmResult<Achievement> field within Goal. Anywhere in Goal where mResult is used, first check if null and requery if needed. This seems like I will be doing a lot of unneccessary querying if I'm using something like a RecyclerView that refetches the object in getItem().
Have a wrapper class that contains a Goal object and the RealmResult<Achievement> as fields. Add a listener to Goal so that anytime a relevant field changes the RealmResult can be requeried.
I'm leaning towards the last one as the cleanest way to keep a valid RealmResult. Am I missing an easier way to accomplish this?
Okay so I'm trying to implement a wrapper class (which I think is similar to the DAO abstraction #EpicPandaForce was mentioning, but I'm not super familiar with that)
public class GoalWrapper {
private RealmResults<Achievements> mResults;
private Goal mGoal;
private Realm mRealm;
public GoalWrapper(Realm realm, Goal goal) {
mRealm = realm;
mGoal = goal;
// TODO: does this need to be removed somewhere? What happens when GoalWrapper gets GC'd?
goal.addChangeListener(new RealmChangeListener<RealmModel>() {
#Override
public void onChange(RealmModel element) {
// rerun the query
findResultForGoal();
}
});
findResultForGoal();
}
/**
* Run a query for the given goal and calculate the result
*/
private void findResultForGoal() {
mResults = mRealm.where(Achievement.class)
.greaterThanOrEqualTo("date", mGoal.getStartDate())
.lessThanOrEqualTo("date", mGoal.getEndDate())
.equalTo("type", mGoal.getAchievementType())
.findAll();
calculateStats();
}
private void calculateStats() {
// Get relevant stats from mResult...
}
}
I haven't tested this code yet but I plan to have a RecyclerView.Adapter with an ArrayList of GoalWrapper objects.
My one concern is that I never remove the listener on mGoal. Do I even need to remove it? What happens in the case that the ArrayList gets GC'ed? I would think that the Goal field and resulting listeners attached to it all get GC'ed as well.

AsyncTask vs ContentProvider. What to use when accessing SQLite database?

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.

ORMLite OpenHelper DAO caching in DaoManager?

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.

Android - Using Dao Pattern with contentProvider

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.

Categories

Resources