64018

Get Last Item in nested database firebase android

Question:

This is my data structure: <a href="https://i.stack.imgur.com/ulzd5.png" rel="nofollow"><img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/ulzd5.png" data-original="https://i.stack.imgur.com/ulzd5.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" /></a>

Here I want to retrieve the <strong>Latitude and Longitude</strong> of the last item of <strong>Location child</strong> based on the <strong>id = "sd"</strong>.

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

Answer1:

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

Recommend