# Reusing Code With Database Cursors

I find myself using this bit of code very often when I am retrieving the results from a Cursor

SearchItem searchItem = new SearchItem();
searchItem.setId(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_ID)));
searchItem.setOrigin(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_ORIGIN)));
searchItem.setDestination(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_DESTINATION)));
searchItem.setTimeStamp(cursor.getLong(cursor.getColumnIndex(COLUMN_NAME_TIMESTAMP)));


Specifically this could be when I am using a CursorAdapter for a ListView and in a DAO object.

What would be a useful design pattern to use in this case?

My first instinct is to have a singleton class which does this. Are there any problems in taking this route?

• I see I was voted down. I am always open to hear why this is a bad question – jiduvah Oct 3 '13 at 2:41
• Not sure, but perhaps the voter believed that this type of question leads to discussions of "equally-right" answers, which is discouraged by SO (see stackoverflow.com/help/dont-ask). – Paul Burke Oct 3 '13 at 3:46
• I didn't realise it was one of those questions. Maybe I should try something and post on codereview – jiduvah Oct 3 '13 at 3:55
• Is those five lines exactly the same when you write them? – Simon Forsberg Nov 22 '13 at 1:07
• yes exactly the same – jiduvah Nov 25 '13 at 3:09

I am not completely sure if your question is as easy as it sounds (or if I am missing something), but here's my thought on things.

Using a singleton class for this does not make much sense in my opinion. There's no state to be stored, and therefore there's no need for an object at all. Instead, it sounds like you could put it in an utility method.

public static SearchItem createSearchItem(Cursor cursor) {
SearchItem searchItem = new SearchItem();
searchItem.setId(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_ID)));
searchItem.setOrigin(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_ORIGIN)));
searchItem.setDestination(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_DESTINATION)));
searchItem.setTimeStamp(cursor.getLong(cursor.getColumnIndex(COLUMN_NAME_TIMESTAMP)));
return searchItem:
}