Convert database cursor To Java Bean - Android Database

Android examples for Database:Cursor Convert

Description

Convert database cursor To Java Bean

Demo Code


//package com.java2s;
import android.database.Cursor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {

    public static <T> T cursorToBean(Cursor cursor, Class<T> cls) {
        T bean = null;/*from   w ww.  jav a 2s.co m*/
        if (cursor != null && cursor.getCount() > 0) {
            Field[] fields = cls.getDeclaredFields();
            String[] columns = cursor.getColumnNames();
            try {
                while (cursor.moveToNext()) {
                    bean = cls.newInstance();
                    for (String column : columns) {
                        Field field = findFieldByName(fields, column);
                        String letter = column.substring(0, 1)
                                .toUpperCase();
                        String setter = "set" + letter
                                + column.substring(1);
                        Method setMethod = cls.getMethod(setter,
                                new Class[] { field.getType() });
                        setMethod.invoke(bean,
                                getValueByField(cursor, column, field));
                    }
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
        return bean;
    }

    private static Field findFieldByName(Field[] fields, String name) {
        for (Field field : fields) {
            if (field.getName().equals(name)) {
                return field;
            }
        }
        return null;
    }

    private static Object getValueByField(Cursor cursor, String columnName,
            Field field) {
        int index = cursor.getColumnIndex(columnName);
        if (index == -1)
            return null;
        Class fieldClass = field.getType();

        if (fieldClass == String.class)
            return cursor.getString(index);

        else if (fieldClass == int.class || fieldClass == Integer.class)
            return cursor.getInt(index);
        else if (fieldClass == Long.class)
            return cursor.getLong(index);

        else if (fieldClass == Double.class)
            return cursor.getDouble(index);

        else if (fieldClass == Float.class)
            return cursor.getFloat(index);

        else if (fieldClass == Short.class)
            return cursor.getShort(index);

        return null;
    }
}

Related Tutorials