This is my data structure:
Here I want to retrieve the Latitude and Longitude of the last item of Location child based on the id = "sd".
Here's the code:
Query query = mDatabase.child("Users").orderByChild("Id").equalTo(busId);
// busId = "sd"
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot user : dataSnapshot.getChildren()) {
Query lastItem = user.getRef().child("Location").orderByKey().limitToLast(1);
lastItem.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String lat = dataSnapshot.child("Latitude").getValue().toString();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
break;
}
}
How can I do that? Thanks
Please use this code for Android:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("Users");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String Id = ds.child("Id").getValue(String.class);
if(Id.equals("sd")) {
Query q = ds.child("Location").getRef().orderByKey().limitToLast(1);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot child : dataSnapshot.getChildren()) {
Double latitude = child.child("Latitude").getValue(Double.class);
Double longitude = child.child("Longitude").getValue(Double.class);
Log.d("TAG", latitude + " / " + longitude);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
q.addListenerForSingleValueEvent(valueEventListener);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(eventListener);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With