Android - 根据子Firebase获取推送密钥

时间:2016-08-06 21:43:25

标签: android firebase nullpointerexception firebase-realtime-database

这就是我的数据:

{
  "courses":{
    "Business":{
        "PushKey_1":{
                "courseC":"B1111",
                "name":"Business Year 1"
        },
        "PushKey_2":{
                "courseC":"B2222",
                "name":"Business Year 2"
        },
    }
  }
}

我试图根据孩子检索推送键。代码I现在尝试:

String testCourseC = "B2222";
String showCourseKey;

        DatabaseReference mRef = FirebaseDatabase.getInstance().getReference().child("courses").child("Business");
        mRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot ds : dataSnapshot.getChildren()){
                    CourseDetails data = ds.getValue(CourseDetails.class);
                    String compareC = data.getCourseC();
                    if (compareC.equals(testCourseC)){
                        showCourseKey = dataSnapshot.getKey();
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        textview1.setText(showCourseKey);

我的CourseDetails课程:

public class CourseDetails {
    private String courseC;
    private String name;

    public CourseDetails() {
    }

    public CourseDetails(String courseC, String name) {
        this.courseC = courseC;
        this.name = name;
    }

    public String getCourseC() {
        return courseC;
    }

    public void setCourseC(String courseC) {
        this.courseC = courseC;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

textview1应显示PushKey_2。如果代码错误,那么textview1不应该显示"课程"?

我从上面的代码中得到了NullPointerException。我已阅读文档并经历了类似的问题,但仍然错了。请不要在意我的愚蠢问题

1 个答案:

答案 0 :(得分:1)

我运行您的代码但没有获得NullPointerException。请发布堆栈跟踪。

我会指出看起来像是错误。

此:

showCourseKey = dataSnapshot.getKey();

应该是:

showCourseKey = ds.getKey();