Reputation: 17
I want to start new activity when a value ("Status") change in my Database Firebase. But i have problem because onActivityCreated is launched three times (because my onDataChange of my Listener is called several times). How can i fix this ? Thank you in advance.
//LISTEN IF THE GAME START ::
mStart = FirebaseDatabase.getInstance().getReference().child("Rooms").child(roomId).child("Proprieties").child("Status");
mStart.addValueEventListener(new ValueEventListener(){
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue().equals("GAME")){
Intent intent = new Intent(WaitGameActivity.this,GameActivity.class);
startActivity(intent);
finish();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
And Log :
V/FA: onActivityCreated
V/FA: onActivityCreated
V/FA: onActivityCreated
Upvotes: 0
Views: 59
Reputation: 164
onDataChange is called multiple times in case you have not removed the listener properly and are creating a new instance of your listener in your activity every time you open it.
Call this once you recieved data:
mStart.removeValueEventListener(this)
Upvotes: 1
Reputation: 9187
You could remove the value listener once you receive an event like below:
mStart.addValueEventListener(new ValueEventListener(){
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
mStart.removeValueEventListener(this); //remove once you get the event
if (dataSnapshot.getValue().equals("GAME")){
Intent intent = new Intent(WaitGameActivity.this,GameActivity.class);
startActivity(intent);
finish();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
Upvotes: 1