2

I'm trying to add chat feature to an Android App with Firebase Realtime DB as storage.

My schema is something like this,

conversation: {
  conversation_id_generated_by_firebase: {
    last_message: {
      message: "hehe"
      type: "text"
      attachments: {0: "url", 1: "url"}
      likes: {0: "uid1", 1: "uid2"}
      created_at: 1245789898
    },
    messages: {
      m1: {
        message: "hehe"
        type: "text"
        attachments: {0: "url", 1: "url"}
        likes: {0: "uid1", 1: "uid2"}
        created_at: 1245789898
      }, m2: {}, m3: {}, m4: {}
    },
    read_till: {
      uid1: 14567894229
      uid2: 14567894228
    },
    created_at: 1456789329
    updated_at: 1456789429
  },
}

Now, How can I fetch multiple conversations with ids in one query/call?

adjuremods
  • 2,938
  • 2
  • 12
  • 17
rpjuvvadi
  • 21
  • 2

2 Answers2

5

There is no Firebase equivalent to SQL's SELECT * WHERE id IN (1,2,3). In Firebase you'll retrieve each item separately.

This is not nearly as slow as most developers think, since Firebase can efficiently pipeline such requests over a single connection. See my answer here for a longer explanation (and some ASCII art): Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly

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

By retrieving ID do you mean you want to retrieve "conversation_id_generated_by_firebase", If yes, i have implemented somewhat similar thing, have modified code as per your DB details. If you could provide some code from what you have tried i can help you further.

    ArrayList<String> keyList = new ArrayList<>();

    // i am assuming you have Chat Object for each conversation
    ArrayList<Chat> chatList = new ArrayList<>();

    myRef = database.getReference().child("conversation");
    ValueEventListener chatListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
        //will be called every time a new conversation is added

          if(dataSnapshot != null){
              for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {  
                String key = postSnapshot.getKey();

                //store key(your id) in array list
                keyList.add(key);


                //now i am assuming you have an object of chat message
                Chat chat = postSnapshot.getValue(Chat.class);

                //add all conversation to chatList ArrayList
                chatList.add(chat);
               }
           }
        }



        @Override
        public void onCancelled(DatabaseError databaseError) {
         //handle error incase something fails
        }
    };
    myRef.addValueEventListener(chatListener);
Ashwin Sinha
  • 85
  • 2
  • 9