Getting all meanings of field in ArrayList | Firebase

前端 未结 2 1462
别跟我提以往
别跟我提以往 2021-01-26 13:51

I am using Firebase Realtime database in my Android app. How can I query field Ingridients in my database and get all meanings in ArrayList

相关标签:
2条回答
  • 2021-01-26 14:12

    Although Firebase Realtime database can store arrays, it does not support querying array members or updating single array elements. So to solve this, I recommend you an alternative database structure that looks like this:

    {
      "Receptes" : {
        "Ingridients" : {
          "Carrot" : true,
          "Salt" : true,
          "Apples" : true
        },
        "Name" : "Food"
      }
    }
    

    As you can see, now the Receptes and the Ingridients are stored as a Maps and not as an arrays. And to query your database to display all ingridients, please use the following code:

    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference ingridientsRef = rootRef.child("Receptes").child("Ingridients");
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                String ingridient = ds.getKey();
                Log.d("TAG", ingridient);
            }
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {}
    };
    ingridientsRef.addListenerForSingleValueEvent(valueEventListener);
    

    According to your comment, the database should look like this:

    {
      "Receptes" : {
        "Ingridients" : {
          "IngridientIdOne" : {
            "Carrot" : true,
            "Salt" : true,
            "Apples" : true
          },
          "IngridientIdTwo" : {
            "Strawberries" : true,
            "Sugar" : true,
            "Bananas" : true
          },
        },
        "Name" : "Food"
      }
    }
    
    0 讨论(0)
  • 2021-01-26 14:15
    DatabaseReference recept = FirebaseDatabase.getInstance().getReference("Receptes");
    DatabaseReference vegies = recept.child("Ingridients");
    

    Check the documentation for more explanation.

    You also need to add a listener

    recept.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.i(TAG, dataSnapshot.child("Ingredients").getValue(String.class);
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, "onCancelled", databaseError.toException());
        }
    });
    
    0 讨论(0)
提交回复
热议问题