[英]How to display data from Firestore in a RecyclerView with Android?
[英]How to make auto refreshing on recyclerview Android while getting data from firebase firestore
我添加了一個滑動 SwipeRefreshLayout 但數據僅在我向下滑動刷新時顯示。 如果我不刷新數據沒有顯示。 我希望在創建活動時在后台自動刷新。
這是我的 XML
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rcv_inventoryCars"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
從 firebase 獲取數據后,我將其添加到列表中,並將該列表添加到適配器中。 我嘗試在 onCompleteListener 中添加到適配器,但應用程序崩潰了。
這是我的 Java 代碼
binding.swipeRefreshLayout.setOnRefreshListener(() -> {
adapter.notifyDataSetChanged();
binding.swipeRefreshLayout.setRefreshing(false);
});
firestore.collection("Inventory").document(auth.getCurrentUser().getUid())
.collection("CarDetails")
.get().addOnCompleteListener(task -> {
if (task.isSuccessful()){
for(DocumentSnapshot documentSnapshot : task.getResult()){
carID = documentSnapshot.getString("carID");
title = documentSnapshot.getString("title");
makeYear = documentSnapshot.getString("makeYear");
fuel = documentSnapshot.getString("fuel");
condition = documentSnapshot.getString("condition");
date = documentSnapshot.getString("date");
kmDriven = documentSnapshot.getString("kmDriven");
image = documentSnapshot.getString("imageLink");
InventoryListModel model = new InventoryListModel(carID, title, makeYear, fuel, condition, date, image, kmDriven);
carList.add(model);
}
} else {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
adapter = new InventoryCarListAdapter(this, carList);
binding.rcvInventoryCars.setAdapter(adapter);
adapter.notifyDataSetChanged();
當您調用Query#get()時,這意味着您正在准確地讀取數據庫一次。 如果你想監聽實時更新,那么你應該使用實時監聽器。 以下是文檔:
但在這種情況下,我看不出您使用 SwipeRefreshLayout 的任何原因,因為您總是獲得實時更新,因此不需要任何滑動。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.