0

Currently I have a class called DBAdapter that has an inner class called DatabaseHelper which extends SQLiteOpenHelper. Without the actual implementation it would look like this (in a high level):

public class DBAdapter {
    public Cursor selectAllBooks();
    public List<Book> getAllBooks(); //This would handle the cursor for you
    private class DatabaseHelper extends SQLiteOpenHelper{}
}

This way, the calling activity could simply call dbAdapter.getAllBooks(), as opposed to having to cycle through the cursor themselves.

However, I stumbled upon a SimpleCursorAdapter, and ResourceCursorAdapter where the database (in my case DBAdapter's selectAllBooks()) would return a cursor, and then you would have a class that would handle this cursor.

http://joesapps.blogspot.com/2011/02/customized-listview-data-display-in.html

He uses this function:

private class MyListAdapter extends ResourceCursorAdapter {
    public void bindView(View view, Context context, Cursor cursor){
        ...
        int price = cursor.getInt(cursor.getColumnIndex(DbAdapter.COL_PRICE));
        ...
    }
}

Doesn't this technically not hide all implementation of the database? Here the ListAdapter needs to know of the column names etc., as opposed to my implementation which just returns a list of what they want and then the ListAdapter can do what it wants with it. I also don't need to know what column names I have to grab data from etc. If you call the function getAllBooks() you will simply get a list of books.

Brandon Ling
  • 3,841
  • 6
  • 34
  • 49
  • 1
    Your implementation makes a duplicate copy of the returned data rows, which, if you have a large dataset, can use up a lot of memory. Using cursors is far more efficient. – Eugene S Feb 17 '14 at 16:34
  • In my opinion both are acceptable approaches. As @unluddite says, for large datasets, having data duplicated might be unacceptable. For small datasets I prefer the approach you're using. – Merlevede Feb 17 '14 at 16:38
  • Understood, but am I correct in saying that my approach does hide the implementation better? Also, can you explain better where I am returning a duplicate? Doesn't the cursor object return virtually the same thing as a list of objects? It would contain all the pairs of (column name, data) – Brandon Ling Feb 17 '14 at 16:38
  • I suppose, but what are you really hiding/exposing? Using cursors, the user just needs to know some static constant integer representing the column index for the data they need. This could be part of the public interface your db class exposes. So instead of using `Book.getName()` they would write `MyDB.NAME` where `NAME` is the column index. – Eugene S Feb 17 '14 at 16:42
  • to be honest your DBAdapter should extend ContentProvider, see Notepad sample demo – pskink Feb 17 '14 at 16:43
  • It's a homework assignment, I will be implementing a content provider this week – Brandon Ling Feb 17 '14 at 16:44

0 Answers0