Created
January 19, 2015 11:16
-
-
Save VAdaihiep/e430391c58439bdf3f48 to your computer and use it in GitHub Desktop.
Convert Cursor to ArrayList object
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
/** | |
* convert from cursor to arraylist of object | |
* | |
* @param <E> | |
* | |
* @param cursor | |
* @param class | |
* @return object | |
*/ | |
public static <E> ArrayList<E> cursorToArrayListObject(Cursor cursor, | |
Class<E> output) { | |
ArrayList<E> arrResult = new ArrayList<E>(); | |
E object = null; | |
Field[] arrFields; | |
while (cursor.moveToNext()) { | |
try { | |
Constructor<E> constructor = output.getConstructor(); | |
object = constructor.newInstance(); | |
arrFields = output.getDeclaredFields(); | |
for (Field field : arrFields) { | |
if (Modifier.isFinal(field.getModifiers())) { | |
continue; | |
} | |
if (cursor.getColumnIndex(field.getName()) == -1) { | |
continue; | |
} | |
field.setAccessible(true); | |
Object type = field.getType(); | |
if (type.equals(String.class)) { | |
field.set(object, cursor.getString(cursor | |
.getColumnIndex(field.getName()))); | |
} else if (type.equals(int.class)) { | |
field.set(object, cursor.getInt(cursor | |
.getColumnIndex(field.getName()))); | |
} else if (type.equals(long.class)) { | |
field.set(object, cursor.getLong(cursor | |
.getColumnIndex(field.getName()))); | |
} else if (type.equals(float.class)) { | |
field.set(object, cursor.getFloat(cursor | |
.getColumnIndex(field.getName()))); | |
} else if (type.equals(double.class)) { | |
field.set(object, cursor.getDouble(cursor | |
.getColumnIndex(field.getName()))); | |
} | |
} | |
arrResult.add((E) object); | |
} catch (NoSuchMethodException e) { | |
e.printStackTrace(); | |
} catch (InvocationTargetException e) { | |
e.printStackTrace(); | |
} catch (InstantiationException e) { | |
e.printStackTrace(); | |
} catch (IllegalAccessException e) { | |
e.printStackTrace(); | |
} | |
} | |
cursor.close(); | |
return arrResult; | |
} |
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
public ArrayList<Student> getAllStudents(){ | |
SQLiteDatabase sqLiteDatabase = getReadableDatabase(); | |
Cursor cursor = sqLiteDatabase.rawQuery("select * from " | |
+ TABLE_STUDENT, null); | |
ArrayList<NotificationInfo> result = cursorToArrayListObject(cursor, | |
Student.class); | |
sqLiteDatabase.close(); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment