Failing to Read Nested Data From Firebase Database

后端 未结 2 1378
梦谈多话
梦谈多话 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.
    0 讨论(0)
  • 2021-02-04 22:40
        databaseReference = FirebaseDatabase.getInstance().getReference();
        val ref = database.child("All Categories").child("0").child("recipes")
        
       
        val valueEventListener = object : ValueEventListener {
        override fun onDataChange(dataSnapshot: DataSnapshot) {
             val recipes = dataSnapshot.getValue(Recipes::class.java) // recipes model reading
        }
    
        override fun onCancelled(databaseError: DatabaseError) {
            
        }
    }
    ref.addListenerForSingleValueEvent(valueEventListener)
    
    0 讨论(0)
提交回复
热议问题