简体   繁体   English

为什么即使 Firebase 数据快照包含子项,我的 ArrayList 也是空的

[英]why is my ArrayList empty even though firebase datasnapshot contains children

I am attempting to pull user data from firebase realtime database, the datasnapshot does contain children and data but when I attempt to put this into an array, the array is empty.我正在尝试从 firebase 实时数据库中提取用户数据,数据快照确实包含子项和数据,但是当我尝试将其放入数组时,该数组为空。 I created a user class which contains the properties to match the ones in firebase, overloaded constructors, and some methods.我创建了一个用户类,其中包含与 firebase、重载构造函数和一些方法中的属性相匹配的属性。 It does not extend any class though as I know this would not work with retrieving data from Firebase.它不扩展任何类,但我知道这不适用于从 Firebase 检索数据。

private List<user> usersList = new ArrayList<>();
private DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
private DatabaseReference ref = databaseReference.child("Users");

public List<user> getUsers(){
    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists()){
                Log.i("users", String.valueOf(dataSnapshot.getChildrenCount()));

                for(DataSnapshot child: dataSnapshot.getChildren()){
                    user userRetrieved = child.getValue(user.class);
                    Log.d("USER before array", userRetrieved.getUserName());
                    usersList.add(userRetrieved);
                    for(int i = 0;i < usersList.size(); i++){
                        Log.d("USER", usersList.get(i).getUserName());
                    }

                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.i("ERROR", databaseError.getMessage());
        }
    });

    return usersList;
}

All feedback welcomed.欢迎所有反馈。

The Firebase APIs are asynchronous. Firebase API 是异步的。 addListenerForSingleValueEvent returns immediately, and the callback you pass to it is executed some time later, after query completes. addListenerForSingleValueEvent立即返回,您传递给它的回调会在查询完成后的一段时间后执行。 There is no guarantee how quickly that will happen.无法保证这会发生多快。 Meanwile, your function is returning a list that's initially empty.同时,您的函数正在返回一个最初为空的列表。 You probably have code that's to read it with the assumption that the query has already completed, when it actually hasn't.您可能有代码读取它,假设查询已经完成,但实际上还没有完成。

Bottom line is that you should only deal with the results of the query after the callback has been invoked, not before.最重要的是,您应该只在调用回调之后处理查询结果,而不是之前。

I figured it out, had to make sure my class was conforming to the object being returned from the DB.我想通了,必须确保我的类符合从数据库返回的对象。 First I had to make my user class implement serializable and add @PropertyName() and also make sure all the property names matched exactly what was in the Firebase.首先,我必须让我的用户类实现可序列化并添加@PropertyName()并确保所有属性名称与 Firebase 中的名称完全匹配。

 public List<User> getUsers(){
    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            try{
                for(DataSnapshot childSnapshot: dataSnapshot.getChildren()){
                    User User = childSnapshot.getValue(User.class);
                    usersList.add(User);
                        User[] UserArray = new User[usersList.size()];
                        UserArray = usersList.toArray(UserArray);
                    for(int i = 0;i < usersList.size(); i++){
                        Log.d("NAME", UserArray[i].getUserName());
                    }


                }
            }catch (Exception e){
                Log.d("Error in the try", e.getMessage());
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.i("ERROR", databaseError.getMessage());
        }
    });

    return usersList;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我断言即使元素存在某个元素也包含某个String也会失败? - Why is my assertion that the element contains a certain String failing even though it is there? 为什么即使我只更改方法中的ArrayList而不更改原始ArrayList,我的原始arraylist仍要修改 - Why is my original arraylist amended even though I only make changes to my ArrayList within the method without changing the orignal ArrayList 为什么我的ArrayList为空? - Why is my ArrayList Empty? 当我尝试添加ArrayList元素时,即使它是新的,为什么我的程序仍然存在? - Why does my program say the ArrayList element exists when I try to add it even though it's new? 我的 arraylist 尺寸为零,即使我已经向其中添加了项目 - My arraylist size is a zero even though I've added items to the it DataSnapshot for 循环不附加 Firebase 数据库路径的子级(Android Studio) - Children of Firebase database path are not attached by DataSnapshot for loop (Android Studio) Firebase DataSnapshot,无法检索正确的子项列表 - Firebase DataSnapshot, Can't retrieve the right list of children Firebase 从 DataSnapShot 检索存储的 ArrayList 给出 NullPointerException - Firebase retrieve stored ArrayList from DataSnapShot gives NullPointerException 即使处理了 ArrayList IndexOutOfBoundsException - ArrayList IndexOutOfBoundsException even though handled 为什么即使我将某些东西推入堆栈,堆栈仍是空的? - Why is it saying stack is empty even though I push something into it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM