从Firebase检索键值

时间:2018-07-14 05:32:23

标签: android firebase firebase-realtime-database

如何从Firebase仅检索键值而不是子值。我只想检索“ Comp 232”和“ comp 231”,如图所示。

  • 主题详细信息
    • 比较232
      • 主题名称:数据库
      • 老师姓名:老师1
    • comp 231
      • 受试者名称:微加工剂
      • 老师姓名:老师2

(我想检索comp 232和comp 231)

这是我的代码...但这不起作用:

final ArrayAdapter<String> myArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,myArrayList);
myDataBase = FirebaseDatabase.getInstance().getReference();
myListView = findViewById(R.id.ListView);
myListView.setAdapter(myArrayAdapter);

myDataBase.addChildEventListener(new ChildEventListener() {

    @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            String Value = dataSnapshot.child("Subject Details").getKey();
            myArrayList.add(Value);
            myArrayAdapter.notifyDataSetChanged();
        }

        @Override
        public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            myArrayAdapter.notifyDataSetChanged();
        }

        @Override
        public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

        }

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

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

enter image description here

1 个答案:

答案 0 :(得分:0)

您正在从错误的级别读取数据库。您想开始在/Subject Details上收听,然后将每个孩子添加到列表中:

myDatabase = FirebaseDatabase.getInstance().getReference("Subject Details");
myListView = findViewById(R.id.ListView);
myListView.setAdapter(myArrayAdapter);

myDatabase.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
        String Value = dataSnapshot.getKey();
        myArrayList.add(Value);
        myArrayAdapter.notifyDataSetChanged();
    }
    ...