Created
August 14, 2015 10:36
-
-
Save logcat/15a350eb5dba21cdbb8a to your computer and use it in GitHub Desktop.
Android generic cursor with basic binding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.annotation.TargetApi; | |
import android.database.Cursor; | |
import android.database.CursorWrapper; | |
import android.os.Build; | |
import java.lang.reflect.Field; | |
public class TypedCursor<T> extends CursorWrapper { | |
private Class<T> aClass; | |
public TypedCursor(Cursor cursor, Class<T> aClass) { | |
super(cursor); | |
this.aClass = aClass; | |
} | |
public T current() { | |
try { | |
Field[] fields = aClass.getFields(); | |
T instance = aClass.newInstance(); | |
for (Field field: fields) { | |
int colIndex = getColumnIndex(field.getName()); | |
field.set(instance, getValueAt(colIndex)); | |
} | |
return instance; | |
} catch (Exception e) { | |
throw new RuntimeException(e); | |
} | |
} | |
@TargetApi(Build.VERSION_CODES.HONEYCOMB) | |
private Object getValueAt(int colIndex) { | |
int type = getType(colIndex); | |
switch (type) { | |
case FIELD_TYPE_BLOB: | |
return getBlob(colIndex); | |
case FIELD_TYPE_FLOAT: | |
return getFloat(colIndex); | |
case FIELD_TYPE_INTEGER: | |
return getInt(colIndex); | |
case FIELD_TYPE_STRING: | |
return getString(colIndex); | |
case FIELD_TYPE_NULL: | |
return null; | |
default: | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment