【问题标题】:add entry to ListView from Firebase从 Firebase 向 ListView 添加条目
【发布时间】:2021-03-05 04:27:10
【问题描述】:

早上好,

我正在尝试从 Firestore 获取数据并将其添加到我的 Listview。不幸的是,它不起作用,我不知道为什么。代码运行但没有向我的 Listview 添加任何条目。我的代码如下所示:

    public void createListViewcontent() {

        listView = findViewById(R.id.mylistview);
        final ArrayList<String> Listviewcontent= new ArrayList<String>();
        db.collection("ok")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {               

                            Listviewcontent.add(document.getId());
                            Toast.makeText(kk.this, document.getId() + " => " + document.getData(), Toast.LENGTH_SHORT).show();
                            Toast.makeText(kk.this, "weird", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(kk.this, "failure", Toast.LENGTH_SHORT).show();
                        }
                    }
                });


        ArrayAdapter<String> arrayAdapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Listviewcontent);
        listView.setAdapter(arrayAdapter);

有人有想法吗?

最好的问候 安卓初学者

【问题讨论】:

    标签: java android firebase google-cloud-firestore android-listview


    【解决方案1】:

    您正在从数据库中获取结果,您正在将它们添加到列表中,但您确实没有通知适配器。这就是整个想法,你得到这些物品并在那之后立即通知适配器。所以应该简单地添加以下代码行:

    arrayAdapter.notifydatasetchanged();
    

    for 循环结束后:

    db.collection("ok")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
    
                            Listviewcontent.add(document.getId());
                            Toast.makeText(kk.this, document.getId() + " => " + document.getData(), Toast.LENGTH_SHORT).show();
                            Toast.makeText(kk.this, "weird", Toast.LENGTH_SHORT).show();
                        }
                        arrayAdapter.notifydatasetchanged(); //Notify the adapter
                    } else {
                        Toast.makeText(kk.this, "failure", Toast.LENGTH_SHORT).show();
                    }
                }
            });
    

    您可以在以下帖子的回答中看到一个工作示例:

    【讨论】:

      猜你喜欢
      • 2017-11-02
      • 2021-06-21
      • 1970-01-01
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      相关资源
      最近更新 更多