It may be a little late, but this is what I use. This method updates the base object with non-default properties of the update object. Then, the Realm#insertOrUpdate method is used to update the area database.
public static <T> void updateObject(T base, T update) { Class<?> aClass = base.getClass(); for (Field field : aClass.getDeclaredFields()) { try { field.setAccessible(true); Class<?> fieldType = field.getType(); if (fieldType.isPrimitive()) { if (fieldType.equals(boolean.class)) { if (field.getBoolean(update)) { field.setBoolean(base, true); } } else if (fieldType.equals(int.class)) { if (field.getInt(update) != 0) { field.setInt(base, field.getInt(update)); } } else if (fieldType.equals(long.class)) { if (field.getLong(update) != 0L) { field.setLong(base, field.getLong(update)); } } else if (fieldType.equals(short.class)) { if (field.getShort(update) != (short) 0) { field.setShort(base, field.getShort(update)); } } else if (fieldType.equals(byte.class)) { if (field.getByte(update) != (byte) 0) { field.setByte(base, field.getByte(update)); } } else if (fieldType.equals(float.class)) { if (field.getFloat(update) != 0.0f) { field.setFloat(base, field.getFloat(update)); } } else if (fieldType.equals(double.class)) { if (field.getDouble(update) != 0.0d) { field.setDouble(base, field.getDouble(update)); } } else if (fieldType.equals(char.class)) { if (field.getChar(update) != '\u0000') { field.setChar(base, field.getChar(update)); } } } else { Object newValue = field.get(update); if (newValue != null) { field.set(base, newValue); } } } catch (IllegalAccessException e) { e.printStackTrace(); } } }
- It uses reflection to access all properties.
- Both objects should be separated from the area.
- The object model must have the
@PrimaryKey annotated property in Realm#insertOrUpdate order to do its job. Otherwise, the method requires some configuration.
guness
source share