【发布时间】:2020-01-18 18:34:49
【问题描述】:
我有一个列表视图,它接收对象数组列表并显示在屏幕上,该对象数组列表取自 firebase 中的数据库,当我从数据库中添加或删除文档(对象)时,列表视图会正常更新,当我修改单个对象字段(文档)时,列表视图会在视图中完全重新创建该对象,并在每次修改状态字段时“复制”。
这是我填充列表视图的代码:
usuarios.orderBy("likes", Query.Direction.DESCENDING);
try {
usuarios.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w("Não consegue", "listen:error", e);
return;
}
for (DocumentChange dc : queryDocumentSnapshots.getDocumentChanges()) {
switch (dc.getType()) {
case ADDED:
Log.d("TAG", "New Msg: " + dc.getDocument().toObject(Doenca.class));
doenca = dc.getDocument().toObject(Doenca.class);
doencaArrayList.add(doenca);
break;
case REMOVED:
Log.d("TAG", "Removed Msg: " + dc.getDocument().toObject(Doenca.class));
doenca = dc.getDocument().toObject(Doenca.class);
doencaArrayList.add(doenca);
break;
case MODIFIED:
// doencaArrayList.remove(doencaArrayList.lastIndexOf(doenca));
Log.d("TAG", "Modified: " + dc.getDocument().toObject(Doenca.class));
doenca = dc.getDocument().toObject(Doenca.class);
doencaArrayList.add(doenca);
break;
}
}
ListView listView = (ListView) root.findViewById(R.id.recyclerViewCadPat);
ArrayAdapter adapter = new DoencaAdapter(getActivity(), doencaArrayList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
}catch (NullPointerException e){
Toast.makeText(getActivity(), "Erro interno", Toast.LENGTH_SHORT).show();
}
请注意,有 3 种状态,一种是添加(可以),一种是删除(可以),一种是修改(这会使列表视图复制对象)。
【问题讨论】:
标签: android android-listview google-cloud-firestore