在Firebase中检索嵌套数据 - Android

时间:2017-02-15 18:35:54

标签: android firebase firebase-realtime-database

我刚进入firebase和android的世界。我按照在线教程来设置和获取非嵌套数据,并在列表视图中显示如下:

数据之前:

Before Data

    mListView = (ListView) findViewById(R.id.ListView) ;
    final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStudents);
    mListView.setAdapter(arrayAdapter);
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    myRef = database.getReference().child("Student1");
    myRef.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            String value = dataSnapshot.getValue(String.class);
            String key = dataSnapshot.getKey();
            String totl = key + ": " + value;
            mStudents.add(totl);
            arrayAdapter.notifyDataSetChanged();
        }
    });

我在数据库中添加了带有子字段的Grades字段。我想显示整个student1数据和成绩。当我尝试运行上面的代码。我收到以下错误。

数据后:

After Data

FATAL EXCEPTION: main
              Process: com.adcpnmd.mystudents, PID: 3524
              com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.HashMap to String
                  at com.google.android.gms.internal.zzbqi.zzaD(Unknown Source)
                  at com.google.android.gms.internal.zzbqi.zzb(Unknown Source)
                  at com.google.android.gms.internal.zzbqi.zza(Unknown Source)
                  at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
                  at com.adcpnmd.mystudents.Main$1.onChildAdded(Main.java:39)
                  at com.google.android.gms.internal.zzblz.zza(Unknown Source)
                  at com.google.android.gms.internal.zzbnz.zzYj(Unknown Source)
                  at com.google.android.gms.internal.zzboc$1.run(Unknown Source)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

如何访问整个数据并添加到ListView?或者我是否错误地构建了数据?

先谢谢。

1 个答案:

答案 0 :(得分:5)

尝试更改firebase代码,如下所示:

myRef = database.getReference().child("Student1").child("Grades");
myRef.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        if (dataSnapshot.exists()) {
            String value = dataSnapshot.getValue(String.class);
            String key = dataSnapshot.getKey();
            String totl = key + ": " + value;
            mStudents.add(totl);
            arrayAdapter.notifyDataSetChanged();
        }
    }
});

<强>更新

要访问整个节点Student1,您可以这样做:

首先,我已将您的Class字段重命名为Course,因为Class可能会产生混淆和问题(Android本身会使用它)。因此,使用表示数据的普通对象创建一个Java文件Student.java

public class Student {

    private String Course;
    private String Name;
    private String Percentile;
    private HashMap<String,String> Grades;

    public Student() {

    }

    public Student(String course, String name, String percentile, HashMap<String, String> grades) {
        Course = course;
        Name = name;
        Percentile = percentile;
        Grades = grades;
    }

    public String getCourse() {
        return Course;
    }

    public String getName() {
        return Name;
    }

    public String getPercentile() {
        return Percentile;
    }

    public HashMap<String, String> getGrades() {
        return Grades;
    }
}

接下来,要获取数据,请执行以下操作:

ValueEventListener valueEventListener = new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Student student = dataSnapshot.getValue(Student.class);

                Log.d("TAG","name: "+student.getName());
                Log.d("TAG","percentile: "+student.getPercentile());
                Iterator it = student.getGrades().entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry pair = (Map.Entry)it.next();
                    Log.d("TAG","grade: "+pair.getKey() +  " = "  + pair.getValue());
                    it.remove(); // avoids a ConcurrentModificationException
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        };

myRef = database.getReference().child("Student1");
myRef.addListenerForSingleValueEvent(valueEventListener);