How to get the key of a pushed value

Tags: , , ,



In Firebase Realtime Database on Android, I want to retrieve this id “-Mb1sSv-FCNr9ElxZIwN”.

databaseReference = FirebaseDatabase.getInstance().getReference().child("Registration Data1");
mDBListener = databaseReference.orderByKey().limitToLast(1).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    mTeachers.clear();
    for (DataSnapshot teacherSnapshot : dataSnapshot.getChildren()) {
        Data DB = teacherSnapshot.getValue(Data.class);
        DB.setKey(teacherSnapshot.getKey());
        mTeachers.add(DB);
    }
    mAdapter.notifyDataSetChanged();
    mProgressBar.setVisibility(View.GONE);
}

enter image description here

Answer

It looks to me that KAsr ... dhz1 is the user ID that comes from the authentication process. If so, that UID should also be added to your reference. So to be able to get this id “-Mb1sSv-FCNr9ElxZIwN”, please change the following reference:

databaseReference = FirebaseDatabase.getInstance().getReference().child("Registration Data1");

To:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Registration Data1").child(uid);

Meaning that:

DB.setKey(teacherSnapshot.getKey());

Will set the above key to the “DB” object.



Source: stackoverflow