How to convert Any Object to ContentValues in Android for Sqlite db insertion.

Below code will convert any object to ContentValues that can be used to insert into table.

Step 1: Create table with exactly same fields which object contains.

Step2: Use below code.

public void save(T t) {

    int id = -1;
    HashMap<String, Object> map = new HashMap<>();
    for (Field field : t.getClass().getDeclaredFields()) {
        field.setAccessible(true); // if you want to modify private fields
        try {
            map.put(field.getName(), field.get(t));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    ContentValues contentValues1 = new ContentValues();
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        if (entry.getValue() instanceof Integer) {
            contentValues1.put(entry.getKey(), (Integer) entry.getValue());
        } else {
            contentValues1.put(entry.getKey(), (((String) entry.getValue() == null) ? "" : (String) entry.getValue()));
        }
    }
    getReadableDatabase().insert(t.getClass().getSimpleName(), null, contentValues1);

}

 

 

Leave a comment