android - can't get values out of ondatachange method -
i'm developing android app i'm using firebase database when in got variable in ondatachange method , assign them global variables got null variables when call variables in ondatachange method not null.
public class positionatemarkertask extends asynctask { public arraylist<location> arraylist= new arraylist<>(); public void connect() { //setting connexion parameter final firebase ref = new firebase("https://test.firebaseio.com/test"); query query = ref.orderbychild("longitude"); //get data db query.addlistenerforsinglevalueevent(new valueeventlistener() { @override public void ondatachange(datasnapshot datasnapshot) { //checking if user exist if(datasnapshot.exists()){ (datasnapshot usersnapshot : datasnapshot.getchildren()) { //get each user has target username location location =usersnapshot.getvalue(location.class); arraylist.add(location); //if password true , data storaged in sharedpreferences file , home activity launched } } else{ system.out.println("not found"); } } @override public void oncancelled(firebaseerror firebaseerror) { system.out.println("problem "); } }); } @override protected object doinbackground(object[] params) { connect(); return null; } @override protected void onpostexecute(object o) { super.onpostexecute(o); system.out.println("the firs long is"+arraylist.get(0).getlongitude()); } }
welcome asynchronous programming, messes thought true. :-)
firebase retrieves/synchronizes database automatically in background. work happens on separate thread, don't need , asynctask
. unfortunately means can't wait data.
i typically recommend reframe code "first a, b" "whenever a, b it".
in case, want data , print longitude of first item. reframed is: whenever receive data, print longitude of first item.
query query = ref.orderbychild("longitude"); query.addlistenerforsinglevalueevent(new valueeventlistener() { @override public void ondatachange(datasnapshot datasnapshot) { if(datasnapshot.exists()){ (datasnapshot usersnapshot : datasnapshot.getchildren()) { location location =usersnapshot.getvalue(location.class); arraylist.add(location); } system.out.println("the first long is"+arraylist.get(0).getlongitude()); } else{ system.out.println("not found"); } } @override public void oncancelled(firebaseerror firebaseerror) { system.out.println("problem "); } });
a few things note here:
if you're interested in first item, can limit query 1 item:
query = ref.orderbychild("longitude").limittofirst(1)
. retrieve less data.i recommend using
addvalueeventlistener()
instead ofaddlistenerforsinglevalueevent()
. former keep synchronizing data. means if insert/change longitude of item in list, code automatically retriggered , print (potentially) new first item.
Comments
Post a Comment