Android examples for Database:SQL Query
execute Database Query by Class via reflection
//package com.book2s; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class Main { public static List<Object> executeQuery(Context context, String sql, Class clz) {/*from w w w .j a va 2 s. c o m*/ try { List<Object> result = new ArrayList<Object>(); SQLiteDatabase db = context.openOrCreateDatabase("data.db", context.MODE_PRIVATE, null); Cursor cursor = db.rawQuery(sql, new String[] {}); Method method = clz.getMethod("generateEntity", Map.class); while (cursor.moveToNext()) { Map<String, Object> row = new HashMap<String, Object>(); for (String item : cursor.getColumnNames()) { int type = cursor.getType(cursor.getColumnIndex(item)); switch (type) { case Cursor.FIELD_TYPE_STRING: row.put(item, cursor.getString(cursor .getColumnIndex(item))); break; case Cursor.FIELD_TYPE_INTEGER: row.put(item, cursor.getInt(cursor.getColumnIndex(item))); break; case Cursor.FIELD_TYPE_NULL: row.put(item, null); break; } } result.add(method.invoke(null, row)); } cursor.close(); db.close(); return result; } catch (Exception ex) { ex.printStackTrace(); return null; } } }