如何在childListener上执行Firebase查询(.equalTo(key))并映射到String

时间:2016-06-12 12:14:50

标签: android firebase firebase-realtime-database

我正在进行详细活动,所以我将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(),
}

1 个答案:

答案 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());
            }
        });

Read the documentation

不需要firebase密钥。如果这不能回答你的问题,请重新说明并解释一下你想要实现的目标!

修改

你应该做什么:

  1. 传递来自其他活动的价值,就像你做的那样
  2. 将您的数据库引用导航到...('posts').child(key)
  3. 获取密钥
  4. 下的数据

    您的数据库应该与上面的示例类似,但您应该使用密钥代替12