在Firebase中检索嵌套数据-Android [英] Retrieving nested data in Firebase - Android

查看:49
本文介绍了在Firebase中检索嵌套数据-Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚进入了Firebase和android的世界.我遵循在线教程来设置和获取非嵌套数据,并将其显示在列表视图中,如下所示:

I've just entered into the world of firebase and android. I followed online tutorials to set and get non-nested data and display those in a listview as follows:

数据之前:

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

我在数据库中添加了带有子字段的成绩"字段.我想显示整个学生1数据以及成绩.当我尝试运行上面的代码时.我收到以下错误.

I added a Grades field with sub-fields to the database. I want to display the entire student1 data along with the grades. When I try running the above code. I get the following error.

数据后:

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中?还是我构造的数据不正确?

What should I do for accessing the entire data and adding to my ListView ? Or Am I structuring the data incorrectly ?

在此先感谢.

推荐答案

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

Try to change your firebase code like this:

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,可以执行以下操作:

To access the entire node Student1, you can do this way:

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

First of all, I've renamed your Class field as Course, because Class could generate confusion and problems (it is used by Android itself). So create a Java file Student.java with the plain object that represents your data:

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;
    }
}

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

Next, to get the data, do this way:

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);

这篇关于在Firebase中检索嵌套数据-Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆