Hello, I am new to Android development, so I'm hoping for your understanding. I would like to ask how I can retrieve all data under 'values' and get the sum. As you can see, the 'keys' are random-generated keys, which were sent from an Arduino device to Firebase, but the values being sent to Firebase are correct. I want to get the sum and display it on an Android app in a single TextView. I am using Android Studio as IDE for my Android app.
I've tried other snippets from Stack Overflow as well, but it's too confusing for my level of knowledge in Android and I can't make it work. Thank you.
Try like this, may be this will help to achieve your task.
DatabaseReference ref=FirebaseDatabase.getInstance().getReference();
ref.child("data/values").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int toalSum=0;
if (dataSnapshot.getValue() != null) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
//depending upon what datatype youre using caste to it.
totalSum = totalSum+(int)snapshot.getValue();
}
Log.d("LOG","Toatal sum-"+totalSum)
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this dataSnapshot.getChildrenCount() will return size
DatabaseReference dbref=FirebaseDatabase.getInstance().getReference();
dbref.child("url/values")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int size = dataSnapshot.getChildrenCount(); //Here u can see the count
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To count those values, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference valuesRef = rootRef.child("data").child("values");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int sum = o;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
int value = ds.getValue(Integer.class);
sum = sum + value;
}
Log.d("TAG", sum);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
valuesRef.addListenerForSingleValueEvent(eventListener);
Your outout will be:
1780
try this basic split string.
database.geteDatabase().getReference().child("data").child("values")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//dataSnapshot.getValue().toString() = {a=1,b=2,c=3}
String[] value = dataSnapshot.getValue().toString().split("[{,}]");
String[] getA= value[1].split("="); //value[1]='a=1'
String[] getB= value[2].split("="); //value[2]='b=2'
String[] getC= value[3].split("="); //value[3]='c=3'
//what you want to do here.
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
this can use for other get basic multi value from firebase database.
Related
I want to retrive division and rno from for all key in array and compare those values in array with two other strings. how to do that?
You can get all children. try below code:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference reference = database.getReference();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
String rno = ds.child("rno").getValue().toString();
String div = ds.child("division").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I don't understand your question. But you can play on those who fulfill the requirements of the child and fulfill the conditions.
DatabaseReference roomRef = dbRef.child("Everybody Room List Messages");
ValueEventListener roomEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dsKey : dataSnapshot.getChildren()) {
for (DataSnapshot dsNick : dsKey.getChildren()) {
if (dsNick.child("nick").getValue().toString().equals(Nick)) {
dsNick.child("image").getRef().setValue("");
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
roomRef.addListenerForSingleValueEvent(roomEventListener);
UPDATE
So, if I understand, you need this code:
FirebaseDatabase database = FirebaseDatabase.getInstance();
database.getReference().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot item: dataSnapshot.getChildren()) {
String snapDiv = item.child("division").getValue().toString();
String snapRno = item.child("rno").getValue().toString();
if(snapDiv.equals(divi) && snapRno.equals(roll)){
//Here you can do everythings you need because division and rno value are those you are searching.
}
}
}
});
I can't understand completly your question.
You need to retrieve for each child his division and rno value. After that you need to compare them with other variables. But in the session these variables are 2 and fixed or you need to compare with a list of pairs?
After that, assuming that the above question will be clarify, if strings are matches, you need to update the value of sub1, sub2,...,sub5 fields?
Please, give us more informations to understand your situation and give you more support.
Hi I am trying to display data from multiple nodes in my database on a listview.
What I'm trying to do is display the "detailCategory" and "detailValue" for every type of workout, every time its saved.
Here is the database reference i'm currently using for my app.
currentUserDB = FirebaseDatabase.getInstance().getReference("WorkoutDetails").child("Cardio").child(currentUId);
I know this needs to increment into the further nodes, but i'm not sure how to read from multiple nodes from at one time.
I'm using dataSnapshot to read the data. I have data being read by specific date in another page, using the code below. So the problem might just be with the database reference in this case.
#Override
protected void onStart() {
super.onStart();
currentUserDB.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
cardiosList.clear();
for(DataSnapshot cardioHistorySnapshot : dataSnapshot.getChildren()){
Cardio cardio = cardioHistorySnapshot.getValue(Cardio.class);
cardiosList.add(cardio);
}
CardioHistoryList adapter = new CardioHistoryList(Cardio_History.this, cardiosList);
ListViewCardioHistory.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
As I saw in your comment, that you are "going as far as the date node", according to this, to display the detailCategory and the detailValue, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference dateRef = rootRef.child("WorkoutDetails").child("Cardio").child(currentUId).child(date);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.getChildren()) {
String detailCategory = ds.child("detailCategory").getValue(String.class);
String detailValue = ds.child("detailValue").getValue(String.class);
Log.d("TAG", detailCategory + " / " + detailValue);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
dateRef.addListenerForSingleValueEvent(eventListener);
Where the date is the date under the currentUId, which can be 1-3-2018, 2-3-2018 and so on. And as you can see, to achieve this, we needed to use nested queries.
I have a problem regarding querying the firebase database using a value and getting the specific node. My schema is shown here:
In my schema 'workLocations' belongs to an 'excavationWorks', and 'excavationWorks' belongs to an 'excavationLists'.
That means that the path to a specific workLocation is excavationLists/excavationWorks/workLocations/(specific workLocation)
The problem that I have is that I want to query the workLocations node by the location value (let's say London) and get the parent node (the red circled key which is the key of the specific workLocation).
I have search and read many posts but I haven't managed to make it work.
My code looks like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("workLocations").orderByChild("location").equalTo("London");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot workLoc : dataSnapshot.getChildren()) {
// do something with the individual "issues"
Log.d(TAG, workLoc.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Thank you
To achieve this, you need to query your database twice like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
DatabaseReference workLocationsRef = reference
.child("excavationLists")
.child("excavationWorks")
.child("workLocations");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.getChildren()) {
String key = ds.getKey();
Query query = workLocationsRef.child(key).orderByChild("location").equalTo("London");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
String description = snapshot.child("description").getValue(String.class);
Log.d("description", description);
String partentKey = snapshot.getRef().getParent().getKey();
Log.d("partentKey", partentKey);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(eventListener);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
workLocationsRef.addListenerForSingleValueEvent(valueEventListener);
I am having trouble fetching the custom push id which is created while pushing the value.
I want to fetch "4wJIGRCkYrZqFpb401hSmgHeBOI3" from rated_user node. Any help will be really useful. Thanks in advance.
Lets say database reference for rated_users is this RatedUser
valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
String key = postSnapshot.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
RatedUser.addValueEventListener(valueEventListener);
Use the following code to archive your goal.
private DatabaseReference ref;
ref = FirebaseDatabase.getInstance().getReferenceFromUrl("https://xxxx.firebase.com/rated_users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
String key = dataSnapshot.getKey();
String value = dataSnapshot.child("key").getValue(String.class);
}catch (Exception e) {
String valws = e.getMessage();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
PS:
I did a quick sample it works for me.
All i did was added a foreach loop:
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
Log.e("children" , snapshot.getKey()+"");
}
this gave me the key "4wJIGRCkYrZqFpb401hSmgHeBOI3"
I want to get item in the last node added in firebase database from my Android. You can see on the image below i'm not sure how to get the specific node, because unique key is created by Firebase. How to reference to auto-created node and child inside? Thanks a lot
The last node
Try this:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
Query lastQuery = databaseReference.child("mp").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = dataSnapshot.child("message").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Handle possible errors.
}
});
Hope this helps!
This might work:
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("mp");
Query query = db.orderByKey().limitToLast(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
Log.d("User key", child.getKey());
Log.d("User val", child.child("message").getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// TODO: Handle errors.
}
});
I prefer to write and retrieve data through objects.
MyObject is POJO.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
MyObject myObject = data.getValue(MyObject.class);
Log.i(TAG, data.getKey() + " = " + myObject.toString());
}
}
console.log('last messages', messages[messages.length-1]);