Skip to content

Instantly share code, notes, and snippets.

@achuinard
Created March 29, 2015 05:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save achuinard/60903f423cb37ea8c544 to your computer and use it in GitHub Desktop.
Save achuinard/60903f423cb37ea8c544 to your computer and use it in GitHub Desktop.
public class FirebaseDataSnapshotMapper {
public static void map(Object object, DataSnapshot dataSnapshot) {
try {
final Class<?> aClass = object.getClass();
final Field[] fields = aClass.getDeclaredFields();
for (final Field classField : fields) {
if (classField.isAnnotationPresent(Firemapped.class)) {
classField.setAccessible(true);
final Firemapped annotation = classField.getAnnotation(Firemapped.class);
final DataSnapshot child = dataSnapshot.child(annotation.firebasePath());
if (child != null) {
final Class fieldClassType = classField.getType();
if (fieldClassType == EditText.class) {
if (annotation.valueType() == String.class) {
((EditText) classField.get(object)).setText(child.getValue(String.class));
} else if (annotation.valueType() == Integer.class) {
final Integer value = child.getValue(Integer.class);
((EditText) classField.get(object)).setText(String.valueOf(value));
}
}
}
}
}
} catch (Exception e) {
Log.e(FirebaseDataSnapshotMapper.class.getName(), "Error mapping Firebase object", e);
}
}
}
@Retention(RetentionPolicy.RUNTIME)
public @interface Firemapped {
public String firebasePath();
public Class valueType() default String.class;
}
@Firemapped(firebasePath = "first_name", valueType = String.class)
EditText mFirstName;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment