<Object> 从另一个 ArrayList 复制的 ArrayList 为空,即使有数据



我通过模型类将项目添加到列表中,然后将这些项目添加到ArrayList<Object>中。但是,即使commentsList.size() > 1,我也总是得到零的大小。

我尝试将List转换为ArrayList并尝试添加项目。但大小总是 0 在 ArrayList<Object>.

ArrayList<Comments> commentsList = new ArrayList<>(Arrays.asList(new Comments("username", "time", "date")));

以下是我正在使用的功能。

private ArrayList<Object> getObject() {
    if (getComments() != null && getComments().size()>=1) {
        objects.add(getComments().get(0));
    }
    return objects;
}
public static ArrayList<Comments> getComments() {
    ArrayList<Comments> commentsList = new ArrayList<>();
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Comments");
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            commentsList.clear();
            for (DataSnapshot shot : snapshot1.getChildren()) {
                 Comments comments = shot.getValue(Comments.class);
                 commentsList.add(comments);                          
           }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
    return commentsList;
}

getComments函数中,您正在执行异步操作,该操作是从 Firebase 数据库中检索数据。因此,您的commentsList中实际上没有任何东西。当然,该函数只是初始化一个具有零元素的新ArrayList,并创建一个等待应用程序中接收数据的ValueEventListener。但是,此操作是异步的(在单独的线程中运行(,因此在创建ValueEventListener后,该函数会立即返回空列表。因此,当您尝试在getObject函数中构建ArrayList<Object>时,您也会得到一个空列表。

我建议编写另一个函数,该函数将在从Firebase数据库接收数据后调用onDataChange函数时调用。例如,在与以下内容相同的类中编写一个函数。

void nowCreateArrayListOfObjects() {
    // TODO: Call the getObject function here
}

现在从onDataChange函数调用此函数,如下所示。

public static ArrayList<Comments> getComments() {
    ArrayList<Comments> commentsList = new ArrayList<>();
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Comments");
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            commentsList.clear();
            for (DataSnapshot shot : snapshot1.getChildren()) {
                Comments comments = shot.getValue(Comments.class);
                commentsList.add(comments);
            }
            // Invoke the function here to get the values now
            nowCreateArrayListOfObjects();
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
    return commentsList;
}

希望对您有所帮助!

最新更新