Loading a Cursor Row into a Model

Posted on 28 Apr 2013 by Eric Oestrich

When using a Cursor in Android I prefer to pull out a row into a Java object. The Java objects will mostly be getters and setters, but will also include convenience methods as well. In order to make going from a cursor row into a model instance I create a static method on each model class called fromCursor.

This method will pull out columns into the appropriate member variable. It will only pull out a column if it is in the selected columns.

public class MyModel {
    public static MyModel fromCursor(Cursor cursor) {
        MyModel myModel = new MyModel();

        if (cursor.getColumnIndex("_id") != -1) {

        if (cursor.getColumnIndex("description") != -1) {

        /* ... */

        return myModel;
comments powered by Disqus
Creative Commons License
This site's content is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License unless otherwise specified. Code on this site is licensed under the MIT License unless otherwise specified.