我想获取android firebase中特定子节点内的所有值。我尝试对特定子节点的值进行硬编码,但该值返回为“null”,尽管存在值。日志也不会打印任何值。
我想要孩子们的钥匙和价值“KiOPo3fZzMmzUkbR74Z”
这是我的代码,
databaseReferenceappmnt=FirebaseDatabase.getInstance().getReference().child("Appointments");
databaseReferenceappmnt.child("KiOPo3fZzMmzUkbR74Z").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
String post_image = (String)dataSnapshot.child("anu").getValue();
String post_key =(String)dataSnapshot.child("anu").getKey();
if (post_image != null) {
Log.d("post_image", post_image);
}
else
{
Log.d("nullvalue","null");
}
Log.d("post_key", post_key);
}
catch (Exception e)
{
Log.e("exeptipom",e+"");
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
它打印键但值为null。它进入“其他”部分条件。我不知道我哪里错了。我是firebase的新手。任何帮助都会很棒。提前谢谢。
答案 0 :(得分:0)
您应该使用getter和setter来设置和获取值。
使用getter很容易获得值。
databaseReferenceappmnt=FirebaseDatabase.getInstance().getReference().child("Appointments");
databaseReferenceappmnt.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
Model model = dataSnapshot.getValue(Model.class);
String post_image = model.getPostImage();
String post_key = model.getPostKey();
}
else
{
Log.d("nullvalue","null");
}
Log.d("post_key", post_key);
}
catch (Exception e)
{
Log.e("exeptipom",e+"");
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
你的Model.java应该是这样的
public class Model {
private String postImage;
private String postKey;
public Model(){
}
public void setPostImage(String postImage) {
this.postImage = postImage;
}
public String getPostImage() {
return postImage;
}
public void setPostKey(String postKey) {
this.postKey = postKey;
}
public String getPostKey() {
return postKey;
}
}
使用setter设置值
Model model = new Model();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Appointments");
model.setPostImage(yourEditText1.getText().toString());
model.setPostKey(yourEditText2.getText().toString())
try {
databaseReference.push().setValue(model, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
//Your code
}
});
}
catch (DatabaseException e)
{
Log.d("Error:",e.getMessage());
}