firebase datasnapshot控制孩子们

时间:2017-12-15 05:52:48

标签: android firebase firebase-realtime-database

当没有带if语句的子进程时,如何控制DataSnapshot子进程值。例如,在没有孩子时获取消息

 protected void onStart() {
    super.onStart();
    databaseOrders.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            personList.clear();
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                Person person = postSnapshot.getValue(Person.class);
                personList.add(person);
            }
            recyclerView.setHasFixedSize(true);
            // use a linear layout manager
            mLayoutManager = new LinearLayoutManager(DetailActivity.this);
            recyclerView.setLayoutManager(mLayoutManager);

            personAdapter = new PersonAdapter(DetailActivity.this, personList);
            personAdapter.setClickListener(DetailActivity.this);
            recyclerView.setAdapter(personAdapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

2 个答案:

答案 0 :(得分:2)

首先你必须检查数据快照getValue()不返回null

if(datSnapshot.getValue()!=null){
       for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
            if(postSnapshot.getValue()!=null){
                Person person = postSnapshot.getValue(Person.class);
                personList.add(person);}
            }}

答案 1 :(得分:1)

您可以使用hasChildren来检测dataSnapshot是否有孩子 像

if(!snapshot.hasChildren()){
    // snapshot has no children
}