Get child from unknown key in android firebase - android

I have a database which holds timestamped entries for lifestyle quizzes that a user takes. The schema is as follows where the children of the timestamp are key value pairs corresponding to the users inputs.
-EvcKZHBZ4CVo9yAdlP7ldadCZS03
-2018-03-19 12:19:49
- age: "20"
- exercise_total: "0"
...
-2018-03-18 12:32:44
- age: "20"
- exercise_total: "15"
...
I have an object made called heartScore with member variables corresponding to all of the children of the timestamp. How do I return the data under the first date entry into a object of type heartScore if I don't know the exact date that the quiz was taken?

This should do the trick:
databaseReference.child("userId").limitToFirst(1)
In practice:
FirebaseReference ref = FirebaseDatabase.getInstance().getReference()
ref.child(userId).limitToFirst(1).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
// There will only be one child
HeartScore score = snapshot.getValue(HeartScore.class);
// Return the HeartScore object in a callback or whatever else you want
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Related

Firebase Realtime Database comparing value inside the child notes with another child note

I have a database something like this. How I want to compare the value for all users to get most value.
restaurant
-userUid
-stateUid
-restaurantUid
-price = 9
-restaurantUid2
-price = 10
-stateUid2
-restaurantUid3
-price = 2
As you can see the database there, stateUid price is 19 while stateUid2 price is only 2
So, stateUid has the most price. How to compare them and display the most one. Thank you
EDIT:
I have done something like this, and it's error at return. And the value is not working.
exports.calculateTotal = functions.database.ref('/restaurant/{userUid}/{stateUid}/{restaurantUid}')
.onWrite((change, context) => {
// Only edit data when it is first created.
if (change.before.exists()) {
return null;
}
// Exit when the data is deleted.
if (!change.after.exists()) {
return null;
}
//Get id
const restaurantUid = context.params.restaurantUid;
let totalValue = 0;
change.after.forEach(function (item) {
totalValue += item.child('total').val();
});
console.log(totalValue);
return functions.database.ref('/priceTotal/' + restaurantUid).child('total').set(totalValue);
});
Firebase queries work on a flat list of nodes. A query can contain only a single unknown key, the key of the direct child nodes under the location where you query. In your data structure there are multiple levels of unknown keys, which means that you can't query for the highest price across all of them.
What you can do in your current data structure is query across one state for the restaurant with the highest price. That'd look something like:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("restaurant");
DatabaseReference stateRef = ref.child("userUid").child("stateId");
stateRef.orderByChild("price").limitToLast(1).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
Log.i(TAG, snapshot.getKey()+": "+snapshot.child("price").getValue(Long.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
But you can't search across all states for a user, or even all users. If you want to allow that, you'll have to store all prices in a flat list, like:
restaurant_prices: {
"restaurantid": {
price: 9,
state: "statid",
user: "userid"
}
}
Also see:
Firebase Query Double Nested
Firebase query if child of child contains a value
int totalPrice = 0;
int greaterPrice = 0;
int temp = 0;
DatabaseRefernce restRef = FirebaseDatabase.getInstance().getReference().child("restaurant").child(userUid);
restRef.addValueEventListener(new ValueEventListener(){
onDataChange(Datasnapshot snapshot) {
for(Datasnapshot snap : snapshot) {
String key = snap.getKey();
//This will return you the keys of stateUid
restRef.child(key).addValueEventListener(new ValueEventListener(){
onDataChanged(DatSnapshot datasnapshot) {
//this for loop will iterate through restaurants of that specific state
for(DataSnapshot snap2 : datasnapshot){
totalPrice += (int) snap2..child("price").getValue();
}
//When this loop ends you will get the total price of all restaurants from that state
}
});
//as u see above I mentioned greater price and temp variable
using simple logic of finding greatest number out of two number save the value of greatest integer to the variable every time you loop through state
}
}
}
);
Use nested for loops to iterate from database like above and calculate your prices
Else what you can do is when you are uploading the data of restos - while uploading prices just make an extra node for total price of city and add price of resto every time you upload new resto

How can i retrieve specific list items on Firebase Databse on Android

teamapp-25ba7
schedules
-LHc3zKZhNFLq536dpA1
UID:
date:
details:
time:
title:
-LHc7MBAoNwLWCNgkZ_y
UID:
date:
details:
time:
title:
from the above example of my nodes, i would like to just get details and time values ,my question is how do i retrieve just those 2 values . i tried iterating through all the values but that just gets me everything
Assuming that you want to get the values of details and time properties from all objects and also assuming that the details property is of type String and the time is ServerValue.TIMESTAMP, to solve this please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference schedulesRef = rootRef.child("schedules");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String details = ds.child("details").getValue(String.class);
long time = ds.child("time").getValue(Long.class);
Log.d("TAG", details + " / " + time);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {}
};
schedulesRef.addListenerForSingleValueEvent(valueEventListener);

How to update a child node that contains a specific value in the database

String userID = selectedCharacter.getUserID();
String charID = selectedCharacter.getCharID();
Character editedCharacter = new Character(userID, charID, name, hitPoints, armorClass, level, experience, gold);
databaseRef
.orderByChild("charID")
.equalTo(selectedCharacter.getCharID())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Translate the character to a map of its data
Map<String,Object> updates = editedCharacter.toMap();
// Update ONLY the node with charID = editedCharacter.getCharID()
databaseRef.updateChildren(updates);
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
So I'm trying to update a character's stats in my firebase database. As you can see:
here
the code I'm using is actually putting the update in character's root instead. What am I doing wrong here? I'm unsure of how to find the node with the key as I'm not storing the key anywhere.
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
So your code will need to handle the fact that the snapshot is a list. In the case of Android that means that you loop over snapshot.getChildren():
databaseRef
.orderByChild("charID")
.equalTo(selectedCharacter.getCharID())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
// Translate the character to a map of its data
Map<String,Object> updates = editedCharacter.toMap();
// Update ONLY the node with charID = editedCharacter.getCharID()
child.getRef().updateChildren(updates);
}
}
Instead of databaseRef.updateChildren(updates);
Could you try
databaseRef.child(dataSnapshot.getKey()).setValue(updates)
Then see if it works.

Accessing firebase children without uid

Is it possible to fetch a child from an object without the entire parent in Firebase
For example, a customer registry, where I need all the "name" fields, but I do not have the user "uid". ...
Alex's answer will work (with my comment for good measure).
But you should realize that this downloads all data of all users. There is no way in the Firebase Database to download just one property of each node. So if you want an efficient way to download just the list of names, you should keep precisely that in the database: a list of names.
usernames
uid1: "Fernando"
uid2: "Alex"
That way you can read just the list of names with:
DatabaseReference usernamesRef = FirebaseDatabase.getInstance().getReference().child("usernames");
usernamesRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String uid = childSnapshot.getKey();
String name = childSnapshot.getValue(String.class);
}
Yes it's possible. Please use this code:
DatabaseReference yourRef = FirebaseDatabase.getInstance().getReference().child("usuarios");
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String uId = (String) ds.getKey();
String nome = ds.getChild("nome").getValue(String.class);
list.add(nome);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
You first iterate to get those uid's and after that use them in the DatabaseReference.
Hope it helps.

Firebase query to find a subscriber is not working

This is how my Firebase db looks like.
subscriber
u36eD7PsOaf6uo0CGuGPBjC3Y223
children: false
empty: false
id:"u36eD7PsOaf6uo0CGuGPBjC3Y223"
name: "JACKSON"
smoker:false
I want to find the record which matches id = u36eD7PsOaf6uo0CGuGPBjC3Y223.
Below is my code and its not able to retrieve the record
Query recentPostsQuery = mRef.orderByChild("id").equalTo("u36eD7PsOaf6uo0CGuGPBjC3Y223");
recentPostsQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e("Count ", "" + dataSnapshot.getChildrenCount());
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
subscriber = postSnapshot.getValue(Subscriber.class);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Log.e count statement is returning 1 record which is correct, but looks like my query is wrong, that is why I am unable to fetch record.
Your query must return String value not a object of Subscriber, Complete object of Subscriber exsist at node - u36eD7PsOaf6uo0CGuGPBjC3Y223
// With return String value which is u36eD7PsOaf6uo0CGuGPBjC3Y223
mRef.orderByChild("id").equalTo("u36eD7PsOaf6uo0CGuGPBjC3Y223");

Categories

Resources