如何在Android中将检索到的数据设置为ListView

时间:2016-10-17 11:51:39

标签: android listview firebase firebase-realtime-database

我正在尝试将检索到的数据从Firebase设置为ListView,但它只将最后一个值设置为ListView

这是我的代码:

composer install

如何将所有值设置为从Firebase检索到的listview?

请帮我解决这个问题

1 个答案:

答案 0 :(得分:1)

不要设置listview,而且它是监听器内部的数据模型,你必须在监听器之外定义listview和数据模型。例如:

List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
ListView listView = (ListView) rootView.findViewById(R.id.listView);
// Keys used in Hashmap
String[] from = {"title", "desc", "name"};
int[] to = {R.id.posttitle, R.id.postdesc, R.id.postdate};
SimpleAdapter adapter = new SimpleAdapter(getActivity(), aList, R.layout.layoutarray, from, to);
listView.setAdapter(adapter);

ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            aList.clear();
            for (DataSnapshot child : dataSnapshot.getChildren()) {

                for (DataSnapshot single : child.getChildren()) {
                    Map<String, Object> map = (Map<String, Object>) single.getValue();

                   namerc = (String) map.get("Namerc");
                   // String image = (String) map.get("Imagerc");
                    description = (String) map.get("Description");
                    title=(String) map.get("Title");

                      if (namerc!=null && description!=null && title!=null) {
                          String[] title1={title};
                          String[] desc1={description};
                          String[] name1={namerc};

                          Toast.makeText(getActivity(), description, Toast.LENGTH_SHORT).show();

                         for (int i=0;i<title1.length;i++) {
                             HashMap<String, String> hm = new HashMap<String, String>();
                             hm.put("title", title1[i]);
                             hm.put("desc", desc1[i]);
                             hm.put("name", name1[i]);
                             aList.add(hm);
                         }
                          // Keys used in Hashmap
                          String[] from = {"title", "desc", "name"};

                          int[] to = {R.id.posttitle, R.id.postdesc, R.id.postdate};
                          adapter.notifyDataSetChanged();
                      }
                }
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });