amm965
amm965

Reputation: 459

Firebase iterations are slow

I'm using firebase with android to create a simple chat app. When the user chooses another user to chat with I want to check whether they've chatted together or not.

In onCreate() method I'm retrieving all the rooms that the current user used before, and I'm putting them in an arraylist called MyChatRooms<>. Then I want to check each room to see the users of the room.

The problem is that the loop I'm using to iterate through rooms name is finishing before I'm able to retrieve any data from the database.

I know there's similar questions to mine, but none of the answers worked for me.

Here's the related code:

if (!MYChatRooms.isEmpty()) {
  for (j = 0; j < MYChatRooms.size(); j++) {
    roomref.child(MYChatRooms.get(j)).child("First User").addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot dataSnapshot1) {
        if (!dataSnapshot1.getValue().toString().equals(Username) && dataSnapshot1.getValue().toString().equals(NUsername)) {
          Users += dataSnapshot1.getValue().toString() + ",,, ";
        } else if (dataSnapshot1.getValue().toString().equals(Username)) {
          roomref.child(MYChatRooms.get(j)).child("Second User").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot2) {
              if (dataSnapshot2.getValue().toString().equals(NUsername)) {
                Users += dataSnapshot2.getValue().toString() + ",,, ";
              }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
          });
        }
      }

      @Override
      public void onCancelled(DatabaseError databaseError) {

      }
   });
  }
}

Upvotes: 0

Views: 255

Answers (3)

user49068
user49068

Reputation: 11

Please check the following topic: https://firebase.google.com/docs/database/usage/optimize? In my case, I had added and index column and limited the query in Firebase Rules.

Upvotes: 0

Yahya
Yahya

Reputation: 240

Try to change you database hierarchy or use firestore instead of real time database

Upvotes: 1

M.Waqas Pervez
M.Waqas Pervez

Reputation: 2430

I would suggest that you change the structure of your data. Imagine if a user has 100 chats that means your have to query 200 times to Firebase that of course does not look feasible.

What i would suggest is that your add a recentChat list in every user and whenever a user starts a new chat with someone you add the id of the second user to that list. That way you can track easily with whom the current user has interacted with.

It structure in firebase can look something like this:

  • User
    • recentChats
      • id of the other user

Upvotes: 1

Related Questions