2

Right now I'm developing an android app, and I just started to work with Firebase.

My question is: How can I retrieve data from the firebase database, without use listeners ?

In my game, I'm saving the high scores of all the users, and I need to take the data from the database when user go into "leader-boards" page.

I saw some solutions, which is not good for my case. One of them is:

mRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String value = dataSnapshot.getValue(String.class);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

This solution is not good for me, because I cant afford to my app to go into the server every time high score of user is changing, because if I would have 20,000 people who playing at the same time, then the game will stuck.

so I cant use this listener, because it will make the game very slow.

My goal is to to find a way to change the high score, without alerting the other people who is currently playing the game, I mean that I need to update every user score for his own, and when user go to the "leader boards" page, only then I will go to the server.

what is the right solution here ?

Or can I use this listener in another way?

If my question is not clear, then ask me in the comment please.

Thank you !!

my lines:

 public static void setUserHighScoreToServer(Context context,boolean isClassic,int scoreNum)
{
    com.firebase.client.Firebase mRef;
    mRef= new com.firebase.client.Firebase("...");
    String name = InternalStorage.getUserName(context);
    String classic = "";
    if(isClassic)classic="Classic";
    else classic="Arcade";
    com.firebase.client.Firebase mRefChild = mRef.child(name+classic);
    mRefChild.setValue(String.valueOf(scoreNum));


}
Levi Omer
  • 115
  • 11

2 Answers2

3

This is the OFFICIAL way to retrieve data once without listening for data changes.

 // Add all scores in ref as rows 

scores.addListenerForSingleValueEvent( new ValueEventListener() { 
    @Override 
    public void onDataChange(DataSnapshot snapshot) {
        for (DataSnapshot child : snapshot.getChildren()) { 
            ... 
        } 
    }
}

more information here: https://firebase.google.com/docs/reference/android/com/google/firebase/database/DataSnapshot

Angel Koh
  • 12,479
  • 7
  • 64
  • 91
sabsab
  • 1,073
  • 3
  • 16
  • 30
1

If you don´t need to update on real time, you can always do a Rest api call to your database. Just do a GET call to retrieve your data

https://[PROJECT_ID].firebaseio/[path].json

and you are good to go You can also update or create new keys using rest api calls.

hacksy
  • 830
  • 5
  • 14