简体   繁体   中英

Realtime database using firebase - retrieving a specific information

So I am trying to create a real-time multiplayer quiz. I am using the Google Real-time Multiplayer API together with the firebase real-time database.

At the beginning of the game, users are prompted to ask themselves a question and provide two answers, where 1 answer is correct. Then this information is sent do Firebase Real-time Database under the child "Games" -- "mRoomId" --- "userId"

The variable uniqueRoomID is the specific id of the room which they players are retrieving from the Google API.

DatabaseReference myRef = database.getReference("Games").child(mRoomId).child(userId);

And I send 4 values with the setValue function to that specific reference.

Upload upload = new Upload(question,answer1,answer2, userId);

 myRef.setValue(upload);

My database tree is as follows

我的实时数据库结构

My question is:

When I present a question to the other user later in the game, I don't want to show my own question, only the other user's question is relevant.

This is my valueEventListener:

 myReference = FirebaseDatabase.getInstance().getReference().child("Games").child(mRoomId);
  myReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
      showData(dataSnapshot);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
  });

And this is the method showData();

private void showData (DataSnapshot dataSnapshot){

for(DataSnapshot ds : dataSnapshot.getChildren()){

  Upload upload = ds.getValue(Upload.class);
  Log.d("TAG", "question1 is  " + upload.getQuestion1() );

}

}

The log in showData is returning two different questions from the database because it loops through the children.

How do I get only one of the questions that is relevant to be presented to the user playing the game ?

Should I structure this differently, or is there a way to get only the values that are relevant to me?

There is no way to exclude a specific child node from a query. This means that (as far as I can see) you have two basic options:

  1. Read both child nodes, and remove your own node client side based on the fact that its DataSnapshot.getKey() has the same value as User.getUid() .
  2. Read only the child node of the other player. This requires that you somehow already know the key/UID of the other player, but would allow you to then load only that player's data with DatabaseReference theirRef = database.getReference("Games").child(mRoomId).child(otherPlayerUid);

Also see:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM