我正在进行详细活动,所以我将DatabaseReference FireKey作为getExtras传递,这是有效的,我想查询子项并映射数据,但我收到错误
UncaughtException: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at graph.app.com.foodgraph.MealDetailsActivity$1.onChildAdded(MealDetailsActivity.java:130)
这是我的代码
mDatabase.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Intent i = getIntent();
final String key = i.getExtras().getString("firekey");
System.out.println(dataSnapshot.getRef().equalTo(key) + " value is ");
;
Map<String, Object> newPost = (Map<String, Object>) dataSnapshot.getValue();
if (newPost != null) {
reportSingle = new FoodItem(newPost.get("MEAL_TITLE").toString().trim(),
}
答案 0 :(得分:1)
假设您有一个如下数据库:
{
"post" : {
"key01" : {
"title" : "abc",
"data" : "def"
},
"key02" : {
"title" : "ghi",
"data" : "jkl"
}
}
}
和邮政课程:
class Post {
private String title;
private String data;
public Post(){
// needed for getValue()
}
public String getTitle(){return title;}
public void setTitle(){/*...*/}
public String getData(){return data;}
public void setData(){/*...*/}
}
为了检索#1帖子,您需要执行以下操作:
//在这里获取密钥
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("posts").child(key).addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post value
Post post = dataSnapshot.getValue(Post.class);
// post now has all the values and
// can be used to update the UI
// ...
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
}
});
不需要firebase密钥。如果这不能回答你的问题,请重新说明并解释一下你想要实现的目标!
你应该做什么:
...('posts').child(key)
您的数据库应该与上面的示例类似,但您应该使用密钥代替1
或2
。