I have been trying to get my data for firebase database using java code(non-android). I used same method how I retrieved in android app. But its not getting data.
Firebase firebase = new Firebase("https://------.firebaseIO.com");
firebase.addValueEventListener(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot ds) {
long i = ds.child("Users").getChildrenCount();
userlist = new String[(int)i];
int j = 0;
for( DataSnapshot each_ds : ds.getChildren() ){
userlist[j] = each_ds.child("username").getValue().toString();
System.out.println(userlist[j]);
j++;
}
}
@Override
public void onCancelled(FirebaseError fe) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
The Firebase client makes its connection to the server in a separate thread and starts listening for data there. The main thread of your program continues and exits when there is no more code to execute, which often happens before Firebase gets its first data back (which may take a few seconds).
So you'll have to wait for the data to come back. For test programs I usually do this by inserting a simple
Thread.sleep()
at the end of my program:But in a real program you'd probably want to figure out a better exit condition. For example, here we use a
CountDownLatch
to make the main code wait until the operation is completed:Don't use this approach in Android by the way, as it will block the main/UI thread and leave the app unresponsive.