当我使用侦听器从Firebase检索数据时,方法外的变量变为零。因此,值1总是会更新。如何将值从Firebase获取到变量中?我知道该方法是异步的,但是我仍然在方法内部分配了变量,如何处理它。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.poll);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mVotesRef = mFirebaseDatabase.getReference().child("votes");
mChildEventListner = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if(dataSnapshot.child("votes").exists()) {
bjp = dataSnapshot.child("bjp").getValue(Integer.class);
congress = dataSnapshot.child("congress").getValue(Integer.class);
others = dataSnapshot.child("others").getValue(Integer.class);
nato = dataSnapshot.child("nato").getValue(Integer.class);
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
bjp = dataSnapshot.child("bjp").getValue(Integer.class);
congress = dataSnapshot.child("congress").getValue(Integer.class);
others = dataSnapshot.child("others").getValue(Integer.class);
nato = dataSnapshot.child("nato").getValue(Integer.class);
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) { }
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) { }
@Override
public void onCancelled(DatabaseError databaseError) { }
};
mVotesRef.addChildEventListener(mChildEventListner);
ImageButton bjpButton = (ImageButton)findViewById(R.id.bjp);
bjpButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mVotesRef.child("bjp").setValue(bjp+1);
}
});
final ImageButton congressButton = (ImageButton)findViewById(R.id.congress);
congressButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mVotesRef.child("congress").setValue(congress+1);
}
});