Firebase value event listener not working
In my application I have an id that is supposed to be pulled from the firebase realtime database. If I pulled it out and it sees that there is no id, then it sets the id to 1. I did debug and the id is set to 1, but after the listener is finished, id goes to 0. I don't "I know why or what is causing this, but here is my code.
Listener code:
userRef.child("id").
addSingleValueEventListener(new ValueEventListener() {
@Override public void onDataChange (DataSnapshot dataSnapshot){
try {
String value = dataSnapshot.getValue().toString();
id = Integer.parseInt(value);
} catch (NullPointerException e) {
id = 1; //After this, id is 1
e.printStackTrace();
}
}
@Override public void onCancelled (DatabaseError databaseError){
id = 1;
}
}); //Now id is 0
source to share
Two things come to mind from this question: one is about Firebase listeners, and the other is about removing unnecessary code.
A fundamental feature of Firebase listeners is that they are asynchronous, which means that your code doesn't wait for the result until the next line is executed. So, take a look at the comments in this skeleton code:
userRef.child("id").
addSingleValueEventListener(new ValueEventListener() {
@Override public void onDataChange (DataSnapshot dataSnapshot){
// code here does not get executed straight away,
// it gets executed whenever data is received back from the remote database
}
@Override public void onCancelled (DatabaseError databaseError){
}
});
// if you have a line of code here immediately after adding the listener
// the onDataChange code *won't have run*. You go straight to these lines
// of code, the onDataChange method will run whenever it ready.
So this means that if you want to do something with the data you receive in onDataChange
, you must put that code inside a method onDataChange
(or some other method called from there, or in some other way that executes this code after how the data was sent back).
As for the second part, a slightly simpler way to test for the existence of an int and get the value would be:
@Override public void onDataChange (DataSnapshot dataSnapshot){
if (dataSnapshot.exists()) {
id = dataSnapshot.getValue(Integer.class);
} else {
id = 1;
}
}
source to share
you need to set id = 1 to firebase database using setValue (), try below line of code that might help you
userRef.child("id").
addSingleValueEventListener(new ValueEventListener() {
@Override public void onDataChange (DataSnapshot dataSnapshot){
try {
String value = dataSnapshot.getValue().toString();
id = Integer.parseInt(value);
} catch (NullPointerException e) {
// if id=0 then set id=1 using setvalue()
// this will set value of Id =1 in firebase database
id=1;
userRef.child("id").setValue(id);
log.d(LOG_TAG, e.printStackTrace());
}
}
@Override public void onCancelled (DatabaseError databaseError){
id=1;
userRef.child("id").setValue(id);
}
});
source to share