英文:
onActivityCreated launched three times
问题
//监听游戏开始事件:
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) { }
});
日志:
V/FA: onActivityCreated
V/FA: onActivityCreated
V/FA: onActivityCreated
英文:
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
答案1
得分: 1
你可以在接收到如下事件后移除值监听器:
mStart.addValueEventListener(new ValueEventListener(){
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
mStart.removeValueEventListener(this); // 在获得事件后移除监听器
if (dataSnapshot.getValue().equals("GAME")){
Intent intent = new Intent(WaitGameActivity.this,GameActivity.class);
startActivity(intent);
finish();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
英文:
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) { }
});
答案2
得分: 1
onDataChange被调用多次,如果您没有正确移除监听器并且在每次打开活动时都在活动中创建了新的监听器实例。
在收到数据后调用此方法:
mStart.removeValueEventListener(this)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论