0

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?

Nolan
  • 1,060
  • 1
  • 11
  • 34

1 Answers1

1

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.

Community
  • 1
  • 1
Damodar Periwal
  • 399
  • 1
  • 2
  • 13