在android应用程序的firebase数据库中检索子arraylist

时间:2018-03-30 11:13:46

标签: android firebase firebase-realtime-database

我想知道如何检索数据 请帮忙!谢谢。

这是我在filebase中的数据库结构。

db structure

 mDatabase = FirebaseDatabase.getInstance().getReference().child("chinese");
    mDatabase.keepSynced(true);

    mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
                Log.v(TAG,""+ childDataSnapshot.getKey()); //displays the key for the node
                Log.v(TAG,""+ childDataSnapshot.child("ingredient").getValue());   //gives the value for given keyname
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

2 个答案:

答案 0 :(得分:1)

您使用下面的代码来读取firebase数据库。

 private void initView() {
    mFirebaseInstance = FirebaseDatabase.getInstance();
    mDatabase = mFirebaseInstance.getReference("usersDb/UserTable"); // root node and childNode Name
    mRvData.setLayoutManager(new LinearLayoutManager(this));
    mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                Log.v(TAG,""+ childDataSnapshot.getKey()); //displays the key for the node
                Log.v(TAG,""+ childDataSnapshot.child("ingredient").getValue());   //gives the value for given keyname
            }
         }


        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

答案 1 :(得分:1)

mDatabase = FirebaseDatabase.getInstance().getReference().child("chinese");
mDatabase.keepSynced(true);

mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
                if (childDataSnapshot.child("ingredient").getValue() != null) {
                    ArrayList<String> ingredients = new ArrayList<>();
                    for (DataSnapshot ing : childDataSnapshot.child("ingredient").getChildren()) {
                        ingredients.add(ing.child("ingredient").getValue(String.class));
                    }
                    System.out.println("Gained data: " + ingredients.toString());
                }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

另一种方法是将DataSnapshot值转换为ArrayList:

GenericTypeIndicator<ArrayList<String>> t = new GenericTypeIndicator<ArrayList<String>>() {};
ArrayList<String> ingredients = childDataSnapshot.child("ingredient").getValue(t);