Skip to content

Instantly share code, notes, and snippets.

@smaspe
Last active December 18, 2015 15:28
Show Gist options
  • Save smaspe/5804159 to your computer and use it in GitHub Desktop.
Save smaspe/5804159 to your computer and use it in GitHub Desktop.
public void save(Context context) {
Map<String, Object> mapRepr = asMap();
Parcel p = Parcel.obtain();
p.writeMap(mapRepr);
p.setDataPosition(0);
ContentValues values = ContentValues.CREATOR.createFromParcel(p);
if (id == -1) {
Uri insertUri = context.getContentResolver().insert(
getPath(getClass()), values);
id = Long.parseLong(insertUri.getLastPathSegment());
} else {
context.getContentResolver().update(getPath(getClass(), id),
values, null, null);
}
}
private Map<String, Object> asMap() {
Map<String, Object> res = new HashMap<String, Object>();
Field[] fields = SQLHelper.getFields(getClass());
for (Field field : fields) {
try {
field.setAccessible(true);
TypeHandler handler = TypeHandler.getHandler(field.getType());
res.put(field.getName(), handler.getSQLValue(field.get(this)));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment