Getting Firebase child key under random key - android

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.

Related

how to retrieve data from fire base and assign to a string

I have a database in fire-base. In that I have a child node named "item1", under item1 i have two values
name
prize
I want to retrieve the name of item1 and I want to put it in a string called "foodname". How can I do that?
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("menu");
Here I tried but did not find solution
String foodname; //this string should get the value as "diary milk"
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("menu").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//This will loop through all items. Add variables to arrays or lists as required
for (DatasnapShot snap : dataSnapshot.getChildren())
{
foodname = dataSnapshot.child("name").getValue().toString();
String prize = dataSnapshot.child("prize").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You can fetch each child individually like such. Or you can make use of a Model or a Hashmap to fetch all of the data and then fetch the data you would like based on the Key
Using below code you can get food name
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("menu");
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String foodName = snapshot.child("name").getValue().toString();
String foodPrice = snapshot.child("prize").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Retrieving any data from Firebase requires a correct database reference and eventListeners that can work for what you want.
To know more about eventListeners visit this link.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("menu").child("item1");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// this code will get only details from item1
foodname = dataSnapshot.child("name").getValue(String.class);
String price = dataSnapshot.child("prize").getValue(Integer.class);
//if you want details from multiple items, you have to loop over the child nodes like this
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
foodname = snapshot.child("name").getValue().toString();
String price = snapshot.child("prize").getValue().toString();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

Android + Firebase: retrieve multiple values and get the sum

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.

Firebase query in tree with depth and multiple children

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);

How to get key value under a key?

I want to use the spinner to display the key which under specific username but unfortunately it returns nothing to the spinner. I used an array to store the key value which under the username.
Here's my database structure
Let's said I am rexyou0831 and I just want to retrieve the 2 usernames which under my username but my code return me nothing to the list. un is my current username variables. Please if you got any idea please share it with me thank you.
Hers' my code
db = FirebaseDatabase.getInstance();
cref = db.getReference("chat");
public ArrayList<String> retrieve()
{
final ArrayList<String> Student=new ArrayList<>();
cref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot c:dataSnapshot.getChildren())
{
if(c.getKey().equals(un)){
for(DataSnapshot d: dataSnapshot.getChildren()){
Student.add(d.getKey());
}
}else{
Student.clear();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return Student;
}
To get those usernames under your username, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("chat").child("rexyou0831");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userName = ds.getKey();
list.add(userName);
}
Log.d("TAG", list);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(eventListener);
Your out put will be: [gigi1212, mario123]
Note, that onDataChenge() is called asynchronous which means that is called even before you are adding those keys to the list. As a conslusion, you need to declare and use that list, inside onDataChenge(), otherwise is null.

Get last node in Firebase database Android

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]);

Categories

Resources