从Firebase ChildEventListener中检索所有子项

时间:2017-08-30 10:28:57

标签: android firebase firebase-realtime-database android-recyclerview

我的firebase数据结构如下所示: my_database_structure

我想检索根(news_db)的所有子节点及其各自的值,例如newsTitle,Url等,并在我的recyclerview中将它们显示为列表。

我尝试过使用ValueEventListeners但在logcat中获取空值。这是我检索数据的代码:

newsRootRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot articlesSnapShot  : dataSnapshot.getChildren()){
            if (articlesSnapShot.getValue() != null){

                HashMap<String, String> hashMap = (HashMap<String, String>) articlesSnapShot.getValue();
                String authorFromDB = hashMap.get(0);
                Log.i(TAG, "Title Rcvd is: \t" + authorFromDB);
                String titleFromDB = hashMap.get(0);
                String descFromDB = hashMap.get(0);
                String urlFromDB = hashMap.get(0);
                String urlToImageFromDB = hashMap.get(0);
                String pubAtFromDB = hashMap.get(0);

                NewsItem newsItem = new NewsItem(authorFromDB, titleFromDB, descFromDB, urlFromDB, urlToImageFromDB, pubAtFromDB);
                itemList.add(newsItem);
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

customAdapter = new CustomAdapter(getContext(), itemList);
progress.setVisibility(View.GONE);
recyclerView.setAdapter(customAdapter);

有人可以在这里指导我吗?感谢。

1 个答案:

答案 0 :(得分:0)

要检索这些值,请使用以下代码:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference newsRef = rootRef.child("news_db");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String newsAuthor = ds.child("newsAuthor").getValue(String.class);
            String newsDate = ds.child("newsDate").getValue(String.class);
            String newsDesc = ds.child("newsDesc").getValue(String.class);
            String newsImageUrl = ds.child("newsImageUrl").getValue(String.class);
            String newsTitle = ds.child("newsTitle").getValue(String.class);
            String newsUrl = ds.child("newsUrl").getValue(String.class);
            Log.d("TAG", newsAuthor + " / " + newsDate + " / " + newsDesc + " / " + newsImageUrl + " / " + newsTitle + " / " + newsUrl);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
newsRef.addListenerForSingleValueEvent(eventListener);