When I call listPost(), it will return NULL. I guess it doesn't wait for the listener to fetch the post from the firebase. How can I wait to fetch the post from firebase before arrayPost get returned?
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;
}