How to save users score in firebase and retrieve it in real-time in Android studio
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);
How to store users score in Firebase with android studio and how to access the child node in firebase
To solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("Users").child("Rona");
Map<String, Object> map = new HashMap<>();
map.put("score", 0);
ref.updateChildren(map);
The result will be the addition of the score
property in your database with the value of 0
.
Edit: According to your comment:
but i wanted to access other users to. not just Rona
To solve this, you need to use a query that looks like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Users").orderByChild("username");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> map = (Map<String, Object>) ds.getValue();
map.put("score", 0);
ds.getRef().updateChildren(map);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
query.addListenerForSingleValueEvent(valueEventListener);
Using the above code, you'll be able to update the score
property not only to Rona
but to all the other users.
Retrieving data of currently logged in user using firebase realtime database in android studio
First make the key of user node the id of the user instead of push():
Map<String,Object> map=new HashMap<>();
map.put("name",name.getText().toString());
map.put("course",course.getText().toString());
map.put("email",email.getText().toString());
map.put("uid",uId);
FirebaseDatabase.getInstance().getReference().child("contacts").child(uId)
.setValue(map)
Then when you want to retrieve specific user object u can get the uId from:
String userId = FirebaseAuth.getInstance().getCurrentUser().getUId()
now u can add Listener to this DatabaseRefernce:
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("contacts").child(userId)..... db.addValueEventListener().......
That's it
How to increment value in my firebase database?
for(DataSnapshot dataSnapshot : snapshot.getChildren()) {
if(dataSnapshot.child("name").getValue().toString() == viewHolder.textView.getText()) {
id = dataSnapshot.getKey();
Integer count = snapshot.child(id).child("count").getValue(Integer.class);
databaseReference.child(id).child("count").setValue(count + 1);
break;
}
}
Toast.makeText(naeeb_Ameen_nshat_fnee.this, "done", Toast.LENGTH_SHORT).show();
Retrieve count data from Firebase Java
When you're using the following query:
Query query = usersRef.orderByChild("isSeen").equalTo(true);
Firebase will always return the exact data you are querying, meaning that you'll get all elements that have the isSeen
field set to true
. Please note that there is no way you can query by a negation. So something like this is not possible:
Query query = usersRef.orderByChild("isSeen").notEqualTo(true);
// br>
According to your comment in which you say that you don't have any elements where the isSeen
field is set to true
, then your query will yield no results, and that's the expected behavior.
While @TimothyPham's answer will work, using getChildrenCount()
might be the best solution. Why? Because if you have a lot of messages this operation requires you to read all of them in order to provide a number. The best solution I can think of would be to increment/decrement a counter as explained in my answer from the following post:
- How to save users score in firebase and retrieve it in real-time in Android studio
Edit:
Query query = usersRef.orderByChild("isSeen").equalTo(true);
query.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
long count = task.getResult().getChildrenCount();
Log.d("TAG", "count: " + count);
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
But this code will only work if you have elements in the database that have he isSeen
field is set to true
.
Related Topics
All Com.Android.Support Libraries Must Use the Exact Same Version Specification
Adding External Library in Android Studio
Firebase Data Desc Sorting in Android
How to Implement My Very Own Uri Scheme on Android
Ideal Way to Cancel an Executing Asynctask
Best Use of Handlerthread Over Other Similar Classes
Onsaveinstancestate () and Onrestoreinstancestate ()
How to Save Users Score in Firebase and Retrieve It in Real-Time in Android Studio
Picasso V/S Imageloader V/S Fresco VS Glide VS Coil
How to Build a Horizontal Listview With Recyclerview
Scrollview Vertical and Horizontal in Android
How to Detect When Wifi Connection Has Been Established in Android
Android Broadcastreceiver on Startup - Keep Running When Activity Is in Background
How to Listen For a Webview Finishing Loading a Url