Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Last Item in nested database firebase android

Tags:

This is my data structure: enter image description here

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

like image 946
Sagaryal Avatar asked Jul 24 '17 08:07

Sagaryal


1 Answers

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);
like image 131
Alex Mamo Avatar answered Sep 23 '22 22:09

Alex Mamo