1

In relational databases, I was using a uid column in each table as primary key. In Android code, I was using the following class format:

class A {
    String uid;
    // Other fields
}

I have switched to Firebase DB. I avoid using arrays while saving data to database, so everything is in key-value format, key being the push id created by calling push(). Since there is a key generated by Firebase, I instinctively assume that it is the counterpart for my uid field and I remove uid from the class. The database record seems as follows:

"-KonAikaef0Q0crP0AgK": {
    // All fields of class A except 'uid' in key-value format
}

And class without uid seems as follows:

class B {
    // All fields of class A except 'uid'
}

When I try to retrieve data from Firebase DB, I get DataSnapshot of key-value pairs, all values being an instance of class B. In some cases, I try to code as I did before, for example, I create a List<B>, populate it with values from resultant DataSnapshot, and give this list to an ArrayAdapter<B> to be shown in a ListView. Now, all keys are lost, which is crucial.

How can I overcome the problem I am facing?

  • Should I keep uid as seen here?
  • Should I keep dummy uid field and map key to this field manually at each retrieval?
  • Any other solution...
Mehmed
  • 2,880
  • 4
  • 41
  • 62

1 Answers1

1

Instead of creating a List<B> you should create a Map<String,B> with the keys in the map being the key from the database. That way you can always loop over the entries, or just the keys, or just the values.

If you then just want the values, you get them by map.values().

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Hi Frank, glad you answer my question. Is order in database retained in the map? Plus, how can I use `Map` as data for an adapter? It seems ArrayList cannot be used, but BaseAdapter can (https://stackoverflow.com/a/19467717/876267). – Mehmed Jul 15 '17 at 09:13
  • 1
    Maps are not in a defined order. If you want to retain order, retrieve the data using a `ChildEventListener` which fires `onChildAdded` in order. Or if you use a `ValueEventListener`, loop over the children with `for (DataSnapshot child: dataSnapshot.getChildren())` which also retains the order. To bind to a list view, I recommend you check out [Firebase-UI](https://github.com/firebase/FirebaseUI-Android/tree/master/database), which contains a few pre-made adapters. – Frank van Puffelen Jul 15 '17 at 14:08