I'm creating an app and trying to use Firebase Realtime Database to store the scores for my game. My database has many users, each of which contains a TreeMap with the date as the key and the score as the value. I am trying to have the player click a button and save their score inside the TreeMap. I am having trouble with reading the data in the TreeMap because I want this to be a one time read and not a listener.
I have tried retrieving the map first, updating it, and reuploading it to the database. However, I don't know how to link this to the button click, as online tutorials all seem to use a listener and snapshot.
private void showData(DataSnapshot dataSnapshot){
String name = "";
String age = "";
String number = "";
TreeMap<String, Integer> scores = new TreeMap<>();
for (DataSnapshot ds: dataSnapshot.getChildren()){
User user = new User();
if (ds.child(userID).getValue(User.class).getScores() != null){
ds.child(userID).getValue(User.class).getScores().put(date, totalScore);
scores = ds.child(userID).getValue(User.class).getScores();
}
name = ds.child(userID).getValue(User.class).getUserName();
age = ds.child(userID).getValue(User.class).getUserAge();
number = ds.child(userID).getValue(User.class).getUserPhoneNumber();
}
scores.put(date, totalScore);
User temp = new User(userID, name, age, number, scores);
myRef.child(userID).setValue(temp);
}
This is the solution I had written, but it doesn't incorporate the button click.
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapShot.getValue(User.class);
if(user.getScores()!=null){
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("date", date);
hashMap.put("totalScore", totalScore);
query.child(userId).setValue(hashMap);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
this is how you update the score , you didnt show ur database schema so i i am not clearly give you the exact query.
Related
I have list of contacts in Map object i want to compare each contact into Firebase and retrieve that node if contact matched as value.
Ex: Suppose i have 123,345,567 as 3 contacts i want to get that complete node if contact inside node.
Firebase Structure
-Users
-someId1
-contact:123
-fname:something
-someId2
-contact:345
-fname:something
-someId3
-contact:567
-fname:something
-someId4
-contact:980
-fname:something
How do i retrieve those complete nodes if given contact matched into Firebase node.
I have written something like this
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference reference=rootRef.child("Users");
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (Map.Entry<String, String> singleContact : contacts.entrySet()) {
query=reference.orderByChild("contact").equalTo(singleContact.getKey());
if (dataSnapshot.hasChild(singleContact.getKey()))
userModelObjects.add(dataSnapshot.child(singleContact.getKey()).getValue(FirebaseUserModel.class));
}
}
I am assuming the keys in your map are like the keys in your database:
//your reference
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
//make a listener
ValueEventListener listener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//this loop will extract all the values in every random ID
for(DataSnapshot ds : dataSnapshot.getChildren()){
//extract the values
String contact = ds.child("contact").getValue(String.class);
String fname = ds.child("fname").getValue(String.class);
//check if they exist in the map, and see what you can do.........
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//error getting data
}
};
ref.addValueEventListener(listener);
In my app, users can create a post, and update their profile picture, but when they do, their profile picture of their created posts does not change. I thought I solved it with the following code, but it was not.
Does anyone know how to fix it?
In BD I have the following structure as seen in the image, and in each post id the data of the user id are saved, what I want to do is that regardless of the post id in all children where the userId node is the same To the current user the userPhoto node is updated, I thought that with the image code it would be enough but what it does is create a new child node of Posts but it is not what I am looking for how could I solve what they think.
final DatabaseReference sd = FirebaseDatabase.getInstance().getReference("Posts");
Query query = sd.orderByChild("userPhoto").equalTo(currentUsers.getPhotoUrl().toString());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
HashMap<String, Object> maps = new HashMap<>();
maps.put("userPhoto", ""+mUri);
sd.updateChildren(maps);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
If you want to update the userPhoto under the id, then you can do the following:
final DatabaseReference sd = FirebaseDatabase.getInstance().getReference("Posts");
Query query = sd.orderByChild("userPhoto").equalTo(currentUsers.getPhotoUrl().toString());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
String key = ds.getKey();
HashMap<String, Object> maps = new HashMap<>();
maps.put("userPhoto", ""+mUri);
sd.child(key).updateChildren(maps);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Since you are doing a query, then all you need to do is iterate and then you will retrieve the correct random id, and then use it in the path child(key)
As shown in the image below, I have a database "table" called fridge that has a child called food. food is an array that can contain one or more elements.
I want to access the last node and fetch the food elements and add them in a list, but I couldn't figure out how to do it.
Thank you for your help
You could follow the docs and use the limitToLast() method. Keys in firebase are ordered alphabetically.
You can try this to get the data:
mDatabase.child("fridge").child(fridgeId).child("food").addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String foodItem = postSnapshot.getValue();
foodList.add(foodItem);
}
}
});
First, create a list to store those values.
List<String> food = new ArrayList<>();
Retrieve the last stored food inside each fridge key
mDatabase.child("fridge").child(yourPushID).child("food").limitToLast(1).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
String lastFood = snapshot.getValue(String.class);
//Add your food to the list
food.add(lastFood);
Log.e("Foods found:",""+lastFood);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
Where yourPushID should be how you are generating those random keys to store your food
Where mDatabase is
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
I 'm trying to retrive all Posts(Root child) data..using datasnapshot along with Map.....
but only Problem is- a single entry data is repeated
others entries are not shown..i don't know why?
i think some mistakes occuring here..
pleae help me out, thanks!
My code looks like-
mPostDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot!=null) {
Map<String,Object> all_users_IDs=(HashMap<String,Object>) dataSnapshot.getValue();
//iterate through each user, ignoring their UID
for(Map.Entry<String, Object> entry : all_users_IDs.entrySet()){
//Get single user map
Map singleUser = (Map) entry.getValue();
String date= (String) singleUser.get("Date");
String posted_img= (String) singleUser.get("PostedImage");
String desc= (String) singleUser.get("Description");
holder.setPostedImg(posted_img, getContext());
holder.setDate(date);
holder.setDescription(desc);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
try this..
for (DataSnapshot data : dataSnapshot.getChildren()) {
// code here
}
I want to get the last key of the book node and incremented by a his value++.
I tried this:
myRefVal=databaseBook.getReference("books");
Query lastQuery = myRefVal.limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
idBook = dataSnapshot.getKey();
int counter = 1;
counter = counter + 1;
idBook = idBook + counter;
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
At beginning I had justBook 1 ,after click on addbook button I had book2 but when I tried to add a 3rd time a book the previous book2 values crash and the new ones tackes places on Book2.
I'm using idBook to create node book in Firebase Database
myRefBook.child(idBook).setValue(bookInfos);
Instead of using methods to create keys, I used the push method of firebase that allows you to create random key Node:
private void createBook(String nom_livre,String cat_selected, String type_annonce_selected ) {
bookInfos=new Book(nom_livre,cat_selected,type_annonce_selected);
myRefBook.push().setValue(bookInfos);
}
And I used orderByKey() and dataSnap.getKey() to get the last key displayed:
ref.orderByKey().limitToFirst(2).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<String>();
for (DataSnapshot dataSnap : dataSnapshot.getChildren()) {
Book valueBook = dataSnap.getValue(Book.class);
keyId = dataSnap.getKey();
String titreLivreToDisplay = valueBook.getNom_livre();
String descLivreToDisplay = valueBook.getDesc_livre();
//Do what you want with the key Node
}} });