Failing to Read Nested Data From Firebase Database

后端 未结 2 1377
梦谈多话
梦谈多话 2021-02-04 22:12

I am sending "Appetizers and Snacks" which is in name key from one activity 1 to activity 2.

In activity 2,the data received is simply :

2条回答
  •  迷失自我
    2021-02-04 22:31

    Instead of this:

    databaseReference = FirebaseDatabase.getInstance().getReference("All Categories").child("name").orderByValue().equalTo(received_id).getRef();
    

    You'll want to use:

    Query query = FirebaseDatabase.getInstance().getReference("All Categories").orderByChild("name").equalTo(received_id);
    

    So:

    1. Use orderByChild("name") to tell the database to order all child nodes on the value of their name property.
    2. Use equalTo(...) to then filter down the sorted data.
    3. Remove the getRef() as that actually undoes all your query buildin.

    To then read the data, do:

    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                for (DataSnapshot categorySnapshot: dataSnapshot.getChildren()) {
                    for (DataSnapshot recipeSnapshot: categorySnapshot.child("recipes").getChildren()) {
                        DetailModel p = recipeSnapshot.getValue(DetailModel.class);
                        detailModelList.add(p);
                    }
                }
    
                detailAdapter = new DetailAdapter(DetailCategory.this, detailModelList);
                recyclerView.setAdapter(detailAdapter);
                progressBar.setVisibility(View.INVISIBLE);
            } else {
                Toast.makeText(DetailCategory.this, "No data available !", Toast.LENGTH_SHORT).show();
                progressBar.setVisibility(View.INVISIBLE);
            }
        }
    

    So:

    1. Listen to the entire query we just created.
    2. Then loop over the children of recipes of each node we get back in the snapshot.

提交回复
热议问题