簡體   English   中英

從firebase檢索數據返回NULL

[英]Retrieving data from firebase returning NULL

當我調用listPost()時,它將返回NULL。 我想它不會等待偵聽器從firebase中獲取帖子。 在返回arrayPost之前,我該如何等待從firebase獲取帖子?

public Post[] listPost() {
    ArrayList<Post> list = new ArrayList<Post>();

    // Fetch post from firebase
    postRef.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot snapshot) {
            for(DataSnapshot child : snapshot.getChildren()) {
                String id = child.getKey();
                String title = child.child("title").getValue().toString();
                String content = child.child("content").getValue().toString();
                String date = child.child("date").getValue().toString();
                String status = child.child("status").getValue().toString();

                Post post = new Post();
                post.setId(id);
                post.setTitle(title);
                post.setContent(content);
                post.setDate(date);
                post.setStatus(status);
                list.add(post);
            }
        }

        @Override
        public void onCancelled(FirebaseError error) {
            System.out.println("The read failed: " + error.getMessage());
        }
    });

    // Convert ArrayList to Array 
    Post[] arrayPost = new Post[list.size()]; 
    list.toArray(arrayPost);
    return arrayPost;
}

雖然您可以使用信號量之類的東西將listPost()轉換為同步方法,但這不是Firebase的工作方式。 例如,每次調用addValueEventListener()將添加一個新的監聽器時,您的數據的變化,一旦你每次叫其將被稱為listPost()

如果listPost()方法的目的是在某處更新某些狀態(例如您的UI),則可以直接從onDataChanged()方法更新狀態。 這將確保您只添加一個值事件偵聽器,並且數據中的更新將始終反映在當前狀態中而無需刷新。

// Setup once when your app loads
postRef.addValueEventListener(new ValueEventListener() {

    @Override
    public void onDataChange(DataSnapshot snapshot) {
        ArrayList<Post> list = new ArrayList<Post>();
        for(DataSnapshot child : snapshot.getChildren()) {
            String id = child.getKey();
            String title = child.child("title").getValue().toString();
            String content = child.child("content").getValue().toString();
            String date = child.child("date").getValue().toString();
            String status = child.child("status").getValue().toString();

            Post post = new Post();
            post.setId(id);
            post.setTitle(title);
            post.setContent(content);
            post.setDate(date);
            post.setStatus(status);
            list.add(post);
        }
        // Do something with your list of posts here
        updateSomething(list);
    }

    @Override
    public void onCancelled(FirebaseError error) {
        System.out.println("The read failed: " + error.getMessage());
    }
});

由於您在這里有一個子列表,您也可以在此處使用ChildEventListener ,並對添加的子項,子項更改和子項刪除事件做出反應,以更新您的狀態或UI。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM