Home > Software engineering >  How do I read push ID of a specific child?
How do I read push ID of a specific child?

Time:10-31

enter image description here

I am trying to make an Android application first time using the Firebase Realtime Database.

CodePudding user response:

I guess you want to get the Id of the object at a specific index (like your want to find the id where name is web (just an example))

try the below piece of code

private void getPushId() {
        database.getReference()
                .child(NODE_NAME)
                .addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        for (DataSnapshot snapshot1 : snapshot.getChildren()) {
                            try {
                                YourModel model = snapshot1.getValue(YourModel.class);
                                if (model.getName().equals("YOUR_SPECIFIC_NAME")) {
                                    snapshot1.getKey(); // Save in Mutable Object
                                    break;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {
                        // do nothing
                    }
                });
    }

CodePudding user response:

If you want to read the value of the name field that exists in the objects in the Domains node, then you should create a reference that points to that node and perform a get() call, as seen in the following lines of code:

DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference domainsRef = db.child("Domains");
domainsRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            for (DataSnapshot ds : task.getResult().getChildren()) {
                String name = ds.child("name").getValue(String.class);
                Log.d("TAG", name);
            }
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

The result in the logcat will be:

Android
Web
Flutter
  • Related