I added a swipe SwipeRefreshLayout but the data only show when I swipe down to refresh. If I don't refresh the data didn't show. I want an auto refresh on the background when an activity is created.
This is my 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>
After getting data from the firebase I added it to the list and add that list into the adapter. I try the adding to adapter thing inside the onCompleteListener but the app crashed.
This is my Java code
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();
CodePudding user response:
When you're calling Query#get() it means that you're reading the database precisely once. If you want to listen for real-time updates, then you should use a real-time listener. Here are the docs:
But in this case, I cannot see any reasons why you would use a SwipeRefreshLayout, because there is no need for any swipe since you're always getting real-time updates.