【发布时间】:2019-08-29 09:57:36
【问题描述】:
我想将数据添加到 For-Loop 内的 ArrayList 中,但它不起作用。
我在 Firebase 中有一个 Cloud Firestore,其中包含另一个应用程序的文档集合。这个是为了获取数据并将其放入 Recycler View 中。适配器和所有设置。据我所见,问题在于在 For-Loop 中填充(数组)列表? (同样在这个循环中填写任何数据也不起作用,但我不确定。) 我在使用 cmets 的代码中记录了我的一些尝试和错误。我敢肯定,这一定只是一些小错误,但我真的找不到。 在 For-Loop 外使用完全相同的代码添加数据是可行的,在里面是行不通的(参见“Blah”)
private ArrayList<String> patients;
private String testString;
//-> String einzig zu Testzwecken
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
patients = new ArrayList<>();
textView = findViewById(R.id.textView);
db.collection("Test")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
//patients = new ArrayList<>();
//-> doesn't work
patients.add((document.getData().toString()));
//doesn't work
listData.add(new Data(R.drawable.hohlbrot, "ahjotest"));
//doesn't work (trying to feed the recyclerView more directly)
//Toast.makeText(MainActivity.this, document.getData().toString(), Toast.LENGTH_SHORT).show();
//textView.setText(document.getData().toString());
// -> both work
testString = testString + document.getData().toString();
textView.setText(testString);
// -> works
patients.add("Blah1");
//doesn't work
//Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
//Log.d(TAG, "Error getting documents: ", task.getException());
patients.add("BlahError");
}
}
});
patients.add("Blah2");
//works
好吧,我尝试了几件事,但使用我希望工作的设置,没有错误消息。它只是没有做任何事情。在 RecyclerView 中,“Blah2”的出现与我稍后添加的任何字符串一样。只要不使用 ArrayList,我在 For-Loop(Toast、String-to-TextView、...)中尝试的任何操作都确实有效。
PS:我是菜鸟,请耐心等待-.-
【问题讨论】:
-
你遇到这个问题的原因是因为你的编码好像一切都是从“自上而下”或同步运行的,但实际上并不是因为它是异步返回的 firebase 跨度>
标签: java android android-recyclerview google-cloud-firestore