我正在尝试显示数据库中的数据,但是这样做有问题。我尝试显示的数据保存为“总计”,并保存为int。我试过将其另存为字符串和双精度字,但还是没有运气。理想情况下,我希望显示总计,如果总计超过9,则显示一条消息。这是我到目前为止的结果。
public class Results extends AppCompatActivity {
private DatabaseReference mDatabase;
private FirebaseAuth fAuth;
private Button btn;
private TextView userR;
private TextView num;
private FirebaseUser currentUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
userR = (TextView) findViewById(R.id.userResults);
btn = (Button) findViewById(R.id.generate);
fAuth = FirebaseAuth.getInstance();
currentUser = fAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference().child("FAQ");
}
@Override
public void onStart() {
super.onStart();
ValueEventListener scoreListener = new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
faqinputs FAQInputs = dataSnapshot.getValue(faqinputs.class);
userR.setText(FAQInputs.getTotal());
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
};
mDatabase.addValueEventListener(scoreListener);
}
}
“总计”保存在“常见问题”节点中,该节点保存在“用户”下
数据结构如下: This is a screenshot some data stored under set nodes
以下数据是我用于创建FAQ节点的代码。
private void sendScoreData() {
String currentUserID = fAuth.getUid();
faqinputs FAQInputs = new faqinputs(questionOne, questionTwo, questionThree, questionFour, questionFive, questionSix, questionSeven, questionEight, questionNine, questionTen, total);
mDatabase.child("Users").child(currentUserID).push().child("FAQ").setValue(FAQInputs);
}
}
答案 0 :(得分:1)
要获取total
属性的值,必须在引用中添加所有节点名称,如以下代码行所示:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference totalRef = rootRef.child("Users").child(uid).child("-M4YRj8nbobkuKurbHqC").child("FAQ").child("total");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int total = dataSnapshot.getValue(Integer.class);
Log.d("TAG", "total: " + total);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
totalRef.addListenerForSingleValueEvent(valueEventListener);
logcat中的结果将是:
total: 15
我看到总数是一个数字,但是,如果将其另存为字符串,请使用以下行:
String total = dataSnapshot.getValue(String.class);