循环使用Firebase数据快照并将值存储在数组

时间:2017-06-06 20:11:13

标签: android arrays loops firebase firebase-realtime-database

我正在制作一个简单的Android杂志应用程序,我想迭代使用Firebase DataSnapshot来检索有关杂志的存储信息,并将它们保存在不同的数组中。I used this step by step instructions to retrieve data from Firebase database。我尝试寻找其他问题,但他们没有'帮忙。

 DatabaseReference ref;
        ref=FirebaseDatabase.getInstance().getReference("magazines");
        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                magazineNameSize(5);
                int i = 0;
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Magazine magazine = snapshot.getValue(Magazine.class);
                    dateOfIssue[i] =magazine.getDateOfIssue();
                    magazineCover[i]=magazine.getImageUri();
                    magazineName[i]=magazine.getMagazineName();
                    i++;
                }
            }

2 个答案:

答案 0 :(得分:1)

试试这个:

ArrayList<String> dateOfIssue = new ArrayList<>();
ArrayList<String> magazineCover = new ArrayList<>();
ArrayList<String> magazineName = new ArrayList<>();
DatabaseReference ref;
        ref=FirebaseDatabase.getInstance().getReference("magazines");
        ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

       for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                Magazine magazine = snapshot.getValue(Magazine.class);
                dateOfIssue.add(magazine.getDateOfIssue());
                magazineCover.add(magazine.getImageUri());
                magazineName.add(magazine.getMagazineName());
                //value are store in three different arraylist
            }
        }

答案 1 :(得分:0)

要将这些值存储在dateOfIssue, magazineCover and magazineName数组中,您需要在onDataChange()方法中声明这些数组,否则您将在此方法之外获得null

希望它有所帮助。