从这个firebase数据库读取时,它总是返回null而不是我需要的值。
我试过用String.class以String的形式拉它但它仍然是null。
我需要从数据库中提取的只是int pName
,在这种情况下dfdf
变量将是final FirebaseDatabase aDatabase = FirebaseDatabase.getInstance();
final DatabaseReference mDatabase = aDatabase.getReference();
DatabaseReference myRef = aDatabase.getReference(pName).child("dose");
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
Integer Value = dataSnapshot.getValue(Integer.class);
String peter = Integer.toString(Value);
count.setText(peter);
}
@Override
public void onCancelled(DatabaseError error) {
count.setText("E");
}
});
{{1}}
答案 0 :(得分:1)
尝试更改 -
DatabaseReference myRef = aDatabase.getReference(pName).child("dose");
到 -
DatabaseReference myRef = mDatabase.child(pName).child("dose");
您应该在mDatabase上运行而不是在数据库上运行,并且不要让孩子参考
将听众改为
addListenerForSingleValueEvent
答案 1 :(得分:0)
DatabaseReference myRef = mDatabase.child(pName).child("dose");
如上所述修复参考。
答案 2 :(得分:0)
试试这段代码..
private void readData(){
final FirebaseDatabase aDatabase = FirebaseDatabase.getInstance();
final DatabaseReference mDatabase = aDatabase.getReference();
// Read from the database child() method put your database name
mDatabase.child("dfdf").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
// if i insert data as user class object then it give user.class
// User user = dataSnapshot.getValue(User.class);
Integer Value = dataSnapshot.getValue(Integer.class);
String peter = Integer.toString(Value);
count.setText(peter);
}
@Override
public void onCancelled(DatabaseError error) {
count.setText("E");
}
});
}
答案 3 :(得分:0)
尝试以下方法:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("dfdf");
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
int value = dataSnapshot.child("dose").getValue(Integer.class);
Log.i("Value is:", value);
}
}
@Override
public void onCancelled(DatabaseError error) {
count.setText("E");
}
});
以上内容将检查快照dfdf
是否存在然后进入onDataChange并检索子dose