我想获取日期字段,但下面的代码没有这样做。 Toast显示为null(String date的值)。
public String date;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState){
DatabaseReference rootRef , demoRef;
//database reference pointing to root of database
rootRef = FirebaseDatabase.getInstance().getReference();
//database reference pointing to demo node
demoRef = rootRef.child("dates");
demoRef.child("date").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
date = dataSnapshot.getValue(String.class);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Toast.makeText(getContext() , date , Toast.LENGTH_SHORT).show();
}
答案 0 :(得分:1)
在onDataChange中添加toast:
demoRef.child("date").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
date = dataSnapshot.getValue(String.class);
Toast.makeText(getContext() , date , Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
由于onDataChange
是异步的,它会在完成检索数据之前转移到另一个任务,然后你需要在方法中添加toast。
答案 1 :(得分:0)
使用此代码
ValueEventListener postListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
Post post = dataSnapshot.getValue(Post.class);
// ...
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
有关详细信息,请查看firebase文档
https://firebase.google.com/docs/database/android/read-and-write