无法从嵌套的Hashmap访问值

时间:2018-05-27 22:32:56

标签: android firebase firebase-realtime-database hashmap

从Firebase检索这组数据,我无法获取user_description部分的值。

Firebase数据

enter image description here

final DatabaseReference fb = FirebaseDatabase.getInstance().getReference();

    DatabaseReference complaint = fb.child("complaints");
    complaint.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot data) {

            for (DataSnapshot child : data.getChildren()) {
                Complaint complaint = child.getValue(Complaint.class);

                String key = complaint.complaint_description.keySet().toString();
                String desc= complaint.complaint_description.get(key).get("user_description");
                Log.v("ComplaintFragment", desc);

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.v("ComplaintFragment", databaseError);

        }

收到错误:

    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.HashMap.get(java.lang.Object)' on a null object reference

这是投诉类

public class Complaint implements Serializable  {

HashMap<String, HashMap<String, String>> complaint_description;
String complaint_id;
String complaint_subject;
String facility_name;
String facility_type;
boolean fixed;
int join_staff;
int join_student;
int join_total;
String location_area;
String location_floor;
String note;
boolean sent;
String user_id;

public Complaint() {
}

public Complaint(HashMap<String, HashMap<String, String>> complaint_description, String complaint_id, String complaint_subject, String facility_name, String facility_type, boolean fixed, int join_staff, int join_student, int join_total, String location_area, String location_floor, String note, boolean sent, String user_id) {

   //initialization
}

//set and get methods here

}

我该怎么办? 感谢

1 个答案:

答案 0 :(得分:1)

由于数据库引用错误,您将获得null

您正在访问主树节点投诉

Table

但您需要再访问一个用户ID

的节点
DatabaseReference complaint = fb.child("complaints");

请记住,可以使用FirebaseAuth检索uid

DatabaseReference complaint = fb.child("complaints").child(uid);

让我知道这项工作是否