This is a helper class that helps fill models with data obtained from the database.
public class Util {
public static <M> ArrayList<M> createModel(M model, Cursor cursor) throws IOException {
try {
final Class<?> cls = model.getClass();
final ArrayList<M> result = new ArrayList<>();
while (cursor.next()) {
final Class<?> item = Class.forName(cls.getName());
final M obj = (M) item.newInstance();
final Field[] fields = item.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
final Class<?> type = field.getType();
switch (type.toString()) {
case "int": {
final int value = cursor.getInt(getFieldName(field), 0);
field.setInt(obj, value);
break;
}
default:
//throw new IOException();
continue;
}
}
result.add(obj);
}
return result;
} catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) {
e.printStackTrace();
throw new IOException();
}
}
private static String getFieldName(Field field) {
final fieldName annotation = field.getDeclaredAnnotation(fieldName.class);
return annotation == null ? field.getName() : annotation.name();
}
}
I think my version is very bad, so I want to improve it, but I haven’t yet figured out how to do it.
Usage example:
String query = "SELECT * FROM table_name WHERE;";
Cursor cursor = helper.query(query);
List<Test> test = Util.createModel(new Test(), cursor);