java - Retrieving data from firebase returning NULL -
when call listpost(), return null. guess doesn't wait listener fetch post firebase. how can wait fetch post firebase before arraypost returned?
public post[] listpost() { arraylist<post> list = new arraylist<post>(); // fetch post 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 array post[] arraypost = new post[list.size()]; list.toarray(arraypost); return arraypost; }
while can turn listpost()
synchronous method using semaphores, not way firebase intended work. example, every time call addvalueeventlistener()
add new listener called whenever data changes, once every time called listpost()
.
if purpose of listpost()
method update state somewhere (e.g. ui), can instead update state directly ondatachanged()
method. ensure add 1 value event listener , updates in data reflected in current state without needing refresh.
// setup once when 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); } // list of posts here updatesomething(list); } @override public void oncancelled(firebaseerror error) { system.out.println("the read failed: " + error.getmessage()); } });
since have list of children here can use childeventlistener
here instead , react child added, child changed , child removed events update state or ui.
Comments
Post a Comment