firebase get value from uid after unkown uid

Viewed 53

CABARAN is an unknown Uid. it is not a text. Right now I have the uid, and I want to get value for the tajukPenuh.

Figure 1: Database

This is the code and I still can't get the value.

FirebaseDatabase.getInstance().getReference().child("karangan").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                for (DataSnapshot child : dataSnapshot.getChildren()) {

                Karangan karangan = child.child(karanganID).getValue(Karangan.class);

                if (karangan != null) {
                    String tajukPenuh = karangan.getTajukPenuh();

                    holder.getTextViewKaranganID().setText("Karangan Tajuk: " + tajukPenuh);

                }
            }

        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});
1 Answers

You could in theory do a query like this:

FirebaseDatabase.getInstance().getReference().child("karangan")
  .orderByChild("-LYgFIl4Xiv_Ls51Slvh/uid").equalTo("-LYgFIl4Xiv_Ls51Slvh")
  .addListenerForSingleValueEvent(new ValueEventListener() {

But the problem is that you'd need a lot of indexes in your rules, which may be technically possible, but is unfeasible for most real usage.

Your current data structure makes it easy to find all the child nodes for CABARAN, but it does not make it easy to find CABARAN for a given child node. To allow that use-case to run efficiently, you should expand your data structure with a so-called reverse index that maps back to CABARAN from the value that you know. So something like:

"myIndex": {
  "-LYgFIl4Xiv_Ls51Slvh": "CABARAN",
  "-LzfFIl4Xasas51Slads": "CABARAN",
  "-Lasddas981398asdh1h": "CASITWO"
}

This is an additional data structure, that you will have to keep up to date when you're writing the rest of the data. But with this structure, it now becomes very easy to determine that -LYgFIl4Xiv_Ls51Slvh maps to CABARAN.

For more on this, see my answer here: Firebase query if child of child contains a value

Related