访问Firebase数据库细节子项

时间:2017-06-15 00:06:23

标签: android firebase firebase-realtime-database

enter image description here

我在Firebase数据库中有两个孩子,例如1)学期I笔记和2)第二学期笔记。

我已成功将数据上传到这些子项中,但是当我检索这些项目时,它只返回第一个子项的数据。 Firebase帮助程序代码 - name是我们的第一学期笔记或第二学期笔记的变量

public class FireBaseHelper {
    DatabaseReference db;
    boolean saved;
    String name;
    Query myref;
    ArrayList<Semester> semesters = new ArrayList<>();

    public FireBaseHelper(DatabaseReference db, String n) {
        this.db = db;
        myref=db.orderByChild("model").equalTo(n);
        name = n;
    }

    public boolean save(Semester s) {
        if (s == null) {
            saved = false;
        } else {
            try {
                db.child(name).push().setValue(s);
                myref=db.orderByChild("model").equalTo(name);
            } catch (DatabaseException e) {
                e.printStackTrace();
                saved = false;
            }
            saved = true;
        }

        return saved;
    }

    public void fetchData(DataSnapshot dataSnapshot) {
        Log.i("Getchildcount", String.valueOf(dataSnapshot.getChildrenCount()));
        semesters.clear();

        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            Semester semester = ds.getValue(Semester.class);
            semesters.add(semester);
        }
    }

    public ArrayList<Semester> retrieve() {
        myref.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                fetchData(dataSnapshot);
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                fetchData(dataSnapshot);
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });


        return semesters;
    }
}

我像这样调用retrieve方法

Firebase helper = new FireBaseHelper(db, NameOfDb);
NotesAdapter adapter = new NotesAdapter(this, helper.retrieve());
//this is the list variable noteItem and I set adapter on it
notesItem.setAdapter(adapter);

Model Image of Firebase

1 个答案:

答案 0 :(得分:0)

您需要使用DatabaseReference childItem = mDatabase.child("child_item_name");

Firebase Realtime database Doc