for example searching in circles for a user circle if a data exist I want it DO process 1 and if data doesn't exist I want it to create one then DO process 2 ... but what happens in this code if data doesn't exist it will create one then do process 2 then go back then do process 1 after checking. so how can I stop the listener after process 2. sorry if the circles example is too ambiguous but this is the simplest example I could think of .
Firebase ref= new Firebase("https://XXXXX.firebaseio.com/circles/");
Query queryRef = ref.orderByChild("circalename").equalTo(user.circalename);
ValueEventListener listener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot datasnapshot) {
if (datasnapshot.exists()) { // I don't want to get back here after
//creating the data in the else statement
// DO process 1
}
// if my data doesnt exist I will create one after that STOP listening
else {
// create circle
// do process 2
}
}
What you can do is use addListenerForSingleValueEvent
as it listens to the event only once
i.e. in your case
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if (datasnapshot.exists()) {
// code if data exists
} else {
// code if data does not exists
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Despite Shubham Arora's answer is the best solution for this case, I'm going to show you how to do exactly what you asked with these two solutions that are quite simple:
boolean
boolean
and change it once your condition is met:
query.addListenerForSingleValueEvent(new ValueEventListener() {
boolean processDone = false;
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists() && !processDone) {
// do process 1
} else {
// do process 2
processDone = true;
}
}
@Override public void onCancelled(DatabaseError databaseError) {}
});
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// do process 1
} else {
// do process 2
query.removeEventListener(this);
}
}
@Override public void onCancelled(DatabaseError databaseError) {}
});
Both solutions did work fine for me when I was using ChildEventListener
and Shubham Arora's answer couldn't help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With