1

When using firebase (or any database that aggregates data basing on ids) I nearly always have to keep track of a key of a given value. For example let's assume I have Location class with latitude and longitude fields. When I download if from firebase, besides its two fields, I also want to keep track of the key (node value generated with push() e.g. -K_esEYXNfMBNmgF3fO4) it was downloaded from so I may later update it, delete it etc. I see only two solutions:

  1. Duplicate the data and add key value as another Location class field. That doesn't work nicely because I have to set the key value only after I executed push().

  2. Create generic wrapper class that will keep key and object:

    public class Key<T> {
    
      private final String key;
      private final T value;
    
      public Key(String key, T value) {
          this.value = value;
          this.key = key;
      }
    
      public String key() {
          return key;
      }
    
      public T value() {
          return value;
      }
    }
    

I am using the second approach but it doesn't look really nice. I have this Key class basically throughout all my codebase and when using RxJava plenty of methods have a return type like this: Observable<Key<Location>> and that just looks ridiculous.

Wilder Pereira
  • 2,249
  • 3
  • 21
  • 31
Srokowski Maciej
  • 431
  • 5
  • 15

2 Answers2

2

What you call ridiculous actually looks quite normal to me.

Alternatively you can include the key in the POJO and annotate it with @Exclude to exclude it from the serialization.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

Follow up on @FrankvanPuffelen great answer, do what you want with the below pushkey

Read and Write Data on Android

private void writeNewPost(String userId, String username, String title, String body) {
    // Create new post at /user-posts/$userid/$postid and at
    // /posts/$postid simultaneously
    String key = mDatabase.child("posts").push().getKey();
    Post post = new Post(userId, username, title, body);
    Map<String, Object> postValues = post.toMap();

    Map<String, Object> childUpdates = new HashMap<>();
    childUpdates.put("/posts/" + key, postValues);
    childUpdates.put("/user-posts/" + userId + "/" + key, postValues);

    mDatabase.updateChildren(childUpdates);
}
Tord Larsen
  • 2,670
  • 8
  • 33
  • 76