问题描述
我想在TextView中显示分数的数值,但是应用程序始终关闭。
这是我的代码
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference myRef = database.getReference("users").child(currentFirebaseUser.getUid());
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String valuePoints = dataSnapshot.child("current_points").getValue(String.class);
mTextViewPoints = findViewById(R.id.current_points);
mTextViewPoints.setText(valuePoints);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
// Log.w(TAG,"Failed to read value.",error.toException());
}
});
}```
Other values that contain letters are numbers he displays,but when it comes only to numbers he closes.
Where am I going wrong?
解决方法
Vanderclin Rocha亲爱的
最初,无法在回调ValueEventListener中定义TextView,应在启动视图时定义您。
代码textView中的问题返回null,您可以进行调试并查看它。 这是获取数据并将其设置为TextView的当前方法。
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference myRef = database.getReference("users").child(currentFirebaseUser.getUid());
TextView mTextViewPoints = findViewById(R.id.current_points);
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String valuePoints = dataSnapshot.child("current_points").getValue(String.class);
mTextViewPoints.setText(valuePoints);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
// Log.w(TAG,"Failed to read value.",error.toException());
}
});
}
我希望这对您有帮助