Guest User

Untitled

a guest
Nov 20th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. import android.arch.lifecycle.LiveData;
  2. import android.support.annotation.NonNull;
  3. import android.util.Log;
  4.  
  5. import com.google.firebase.database.DataSnapshot;
  6. import com.google.firebase.database.DatabaseError;
  7. import com.google.firebase.database.DatabaseReference;
  8. import com.google.firebase.database.GenericTypeIndicator;
  9. import com.google.firebase.database.ValueEventListener;
  10.  
  11. public class FirebaseLiveData<T> extends LiveData<T> {
  12.  
  13. private static final String TAG = "FirebaseLiveData";
  14.  
  15. @NonNull
  16. private final DatabaseReference reference;
  17. private final Class<T> type;
  18. private final GenericTypeIndicator<T> typeIndicator;
  19.  
  20. private ValueEventListener listener = new ValueEventListener() {
  21. @Override
  22. public void onDataChange(DataSnapshot dataSnapshot) {
  23. if (type != null) {
  24. setValue(dataSnapshot.getValue(type));
  25. } else if (typeIndicator != null) {
  26. setValue(dataSnapshot.getValue(typeIndicator));
  27. } else {
  28. Log.w(TAG, "no type specified");
  29. //noinspection unchecked
  30. setValue((T) dataSnapshot.getValue());
  31. }
  32.  
  33. }
  34.  
  35. @Override
  36. public void onCancelled(DatabaseError databaseError) {
  37. setValue(null);
  38. }
  39. };
  40.  
  41. public FirebaseLiveData(@NonNull DatabaseReference reference, Class<T> type) {
  42. this.reference = reference;
  43. this.type = type;
  44. typeIndicator = null;
  45. }
  46.  
  47. public FirebaseLiveData(@NonNull DatabaseReference reference,
  48. GenericTypeIndicator<T> typeIndicator) {
  49. this.reference = reference;
  50. this.type = null;
  51. this.typeIndicator = typeIndicator;
  52. }
  53.  
  54. @Override
  55. protected void onActive() {
  56. super.onActive();
  57. reference.addValueEventListener(listener);
  58. }
  59.  
  60. @Override
  61. protected void onInactive() {
  62. super.onInactive();
  63. reference.removeEventListener(listener);
  64. }
  65. }
Add Comment
Please, Sign In to add comment