"how to save users score in firebase and retrieve it in real-time in android studio" Code Answer

3

edit: 29th, june 2020

now it's also possible to solve this problem without the use of a transaction. we can simply increment a value using:

rootref.child("score").setvalue(servervalue.increment(1));

and for decremenet, the following line of code is required:

rootref.child("score").setvalue(servervalue.increment(-1));

this is how you set a value in your firebase database:

databasereference rootref = firebasedatabase.getinstance().getreference();
rootref.child("score").setvalue(1);

assuming that the your score field is of type integer, to solve this, please use the following method:

public static void setscore(string operation) {
    databasereference rootref = firebasedatabase.getinstance().getreference();
    databasereference scoreref = rootref.child("score");
    scoreref.runtransaction(new transaction.handler() {
        @override
        public transaction.result dotransaction(mutabledata mutabledata) {
            integer score = mutabledata.getvalue(integer.class);
            if (score == null) {
                return transaction.success(mutabledata);
            }

            if (operation.equals("increasescore")) {
                mutabledata.setvalue(score + 1);
            } else if (operation.equals("decreasescore")){
                mutabledata.setvalue(score - 1);
            }

            return transaction.success(mutabledata);
        }

        @override
        public void oncomplete(databaseerror databaseerror, boolean b, datasnapshot datasnapshot) {}
    });
}

for this, i recommend you definitely use transactions. you will avoid wrong results if users are trying to increase/decrease the score in the same time. so as a conclusion, call this method accordingly to your increase/decrease operation.

this is how you can read it:

databasereference rootref = firebasedatabase.getinstance().getreference();
databasereference scoreref = rootref.child("score");
valueeventlistener eventlistener = new valueeventlistener() {
    @override
    public void ondatachange(datasnapshot datasnapshot) {
        integer score = ds.getvalue(integer.class);
        log.d("tag", score + "");
    }

    @override
    public void oncancelled(databaseerror databaseerror) {}
};
scoreref.addlistenerforsinglevalueevent(eventlistener);
By Gusdor on August 3 2022

Answers related to “how to save users score in firebase and retrieve it in real-time in android studio”

Only authorized users can answer the Search term. Please sign in first, or register a free account.