【问题标题】:After getting all documents in collection can't add field to ArrayList, Android Studio, Java, Firebase Firestore获取集合中的所有文档后,无法将字段添加到 ArrayList、Android Studio、Java、Firebase Firestore
【发布时间】:2020-06-04 16:21:52
【问题描述】:

大家好,我有一个问题,因为我从 Firebase Firestore 获取整个集合,并希望在每个文档中获取“主题名称”字段并将其添加到 ArrayList 中,然后在 ListView 中显示此主题。它将成为我应用程序的论坛部分的一部分。

但是!

它似乎获取了文档,并读取了它们的字段,正如我在日志中看到的那样

Log.d(TAG, document.getId() + " => " + document.get("topic_name"));

_

D/TAG: 6EvC4SqqDxR4TYelLOKM => Topic 1
KpXLBDzSkAb2u96knG8L => Topic 4
SY49j4RqcOI1v79EIVME => Topic 3
xS0Hw4Rj5KPGj1G7vy7T => Topic 2

它没有将它添加到 ArrayList 中,或者它以某种方式消失了,因为设备不显示列表。

起初我认为这是因为从内部类中访问 ArrayList 时需要将其声明为 final,但事实并非如此,因为我添加了一个测试主题来检查该假设。 (Test Topic 123-Test to Topic 125)并且正常显示,所以ArrayList不是final的。

我尝试将负责 ListView 的整个代码放在 onComplete 方法中,但它似乎不起作用,因为适配器充满了错误,如果可能的话,我想要一些帮助,或者关于如何做到这一点的替代想法.如果我复制了这个主题,我很抱歉我试图寻找答案但无法找到它。

代码如下:

public class Forum extends Activity {

public static final String TAG = "TAG";
FirebaseFirestore db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_forum);


    db = FirebaseFirestore.getInstance();
    final ArrayList<String> forumTopics = new ArrayList<>();

    db.collection("forum_topics")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {

                    if (task.isSuccessful()) {
                        int count = 0;
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            forumTopics.add(count, document.getString("topic_name"));
                            count += 1;
                            Log.d(TAG, document.getId() + " => " + document.get("topic_name"));
                        }

                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });

    String test_string = "Test Topic 123";
    forumTopics.add(0,test_string);
    forumTopics.add(1,"Test Topic 124");
    forumTopics.add(2,"Test Topic 125");
    forumTopics.add(3,"Test Topic 126");

    ListAdapter forumAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, forumTopics);
    ListView forumListView =  findViewById(R.id.ForumListView);
    forumListView.setAdapter(forumAdapter);

    forumListView.setOnItemClickListener(
            new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String topic = String.valueOf(parent.getItemAtPosition(position));
                    Toast.makeText(Forum.this, topic, Toast.LENGTH_LONG).show();
                }
            }
    );
}

This is the output on the device

非常感谢。

【问题讨论】:

  • 我很确定你需要在集合的 onComplete 完成后刷新列表视图。

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


【解决方案1】:

试试这个

db.collection("forum_topics")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {

                    if (task.isSuccessful()) {
                        int count = 0;
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            forumTopics.add(count, document.getString("topic_name"));
                            count += 1;
                             forumTopics.add(document.get("topic_name"));
                        }
                        forumAdapter.notifyDataSetChanged()
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });

    ListAdapter forumAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, forumTopics);
    ListView forumListView =  findViewById(R.id.ForumListView);
    forumListView.setAdapter(forumAdapter);

【讨论】:

  • 谢谢,通知成功了,但你的代码有一些错误,但这个想法奏效了。代码将在您的帖子下方。
  • 错误是由于 bcoz 我没有完整的代码 :P 另外,想法是,在将数据添加到列表后,您必须通知适配器数据集已更改现在你必须刷新。在触发 onComplete() 之前调用适配器初始化,因此您必须通知适配器。
  • 是的,因为你的代码我弄明白了,所以我非常感激,不用担心错误,点击了主要想法,它真的很好用!正如您在下面看到的,我在 onComplete() 之前打开了适配器。但是我仍然没有得到一件事,即使它在下面,该 ArrayList 中仍然应该有一些元素是从 onComplete 开始添加的,但它现在可以工作,这很重要。再次感谢你! :D
  • 我们无法确定 onComplete() 何时被触发。由于我们正在添加回调 CompleteListener ,所以当数据可用时,它将触发完成。因此,无论您在之前还是之后初始化适配器,都必须通知数据更改。这就是回调机制的工作原理。
  • 如果您的问题得到解决,请也为答案投票。
【解决方案2】:

我能够在您的帮助下解决问题,下面是适用于我的解决方案。谢谢所有帮助过我的人,我非常感激,愿你有美好的一天。

    db = FirebaseFirestore.getInstance();
    final ArrayList<String> forumTopics = new ArrayList<>();

    final ListAdapter forumAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, forumTopics);
    ListView forumListView =  findViewById(R.id.ForumListView);
    forumListView.setAdapter(forumAdapter);

    db.collection("forum_topics")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {

                    if (task.isSuccessful()) {
                        int count = 0;
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            forumTopics.add(count, document.getString("topic_name"));
                            count += 1;
                        }
                        ((ArrayAdapter) forumAdapter).notifyDataSetChanged();
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });

    forumListView.setOnItemClickListener(
            new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String topic = String.valueOf(parent.getItemAtPosition(position));
                    Toast.makeText(Forum.this, topic, Toast.LENGTH_LONG).show();
                }
            }
    );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 2021-05-09
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多