我正在使用FirestoreRecyclerAdapter
将数据从Firestore
加载到RecyclerView
。我想显示进度对话框,直到数据完全加载。我该怎么做?提前谢谢。
这是我迄今为止的代码。
void loadPosts() {
FirestoreRecyclerOptions<Post> options = new FirestoreRecyclerOptions.Builder<Post>()
.setQuery(query, Post.class)
.build();
adapter = new FirestoreRecyclerAdapter<Post, DataViewHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull DataViewHolder dataViewHolder, int i, @NonNull Post post) {
dataViewHolder.setData(post.getTitle(), post.getDescription());
}
@NonNull
@Override
public DataViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_post, parent, false);
return new DataViewHolder(view);
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
@Override
protected void onStop() {
super.onStop();
if (adapter != null) {
adapter.stopListening();
}
}
@Override
protected void onStart() {
super.onStart();
if (adapter != null) {
adapter.startListening();
}
}
在FirebaseRecyclerAdapter
构建器中的.setQuery(query)
之前,您可以将侦听器附加到该查询,以了解它何时完成,从而构建RecyclerView
示例
progressDialog.show();
Query query = db.collection("Users").child(my_user_id).addListenerForSingleValue(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Data has been fetched, hide progressDialog , check if data exists at the location with if(dataSnapshot.exists()) if you want to be sure theres something to fetch
progressDialog.hide();
}
@Override
public void onCancelled(DatabaseError databaseError) {
//The fetch failed, dismiss the dialog and show an error message
progressDialog.hide();
}
});
检查查询的方法
虽然Gastón的答案有效,但有一种稍微简单的方法,不需要额外的监听器。CCD_ 7具有当其已经接收到完整的CCD_。
void loadPosts() {
FirestoreRecyclerOptions<Post> options = new FirestoreRecyclerOptions.Builder<Post>()
.setQuery(query, Post.class)
.build();
progressDialog.show();
adapter = new FirestoreRecyclerAdapter<Post, DataViewHolder>(options) {
@Override
public void onDataChanged() {
progressDialog.hide();
}
@Override
protected void onBindViewHolder(@NonNull DataViewHolder dataViewHolder, int i, @NonNull Post post) {
dataViewHolder.setData(post.getTitle(), post.getDescription());
}
@NonNull
@Override
public DataViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_post, parent, false);
return new DataViewHolder(view);
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
另请参阅有关FirestoreRecyclerAdapter
数据和错误事件的FirebaseUI文档。
注意,onDataChanged
可以被调用多次,最初调用一次,然后每次当query
的数据改变时调用。因此,请确保其中的代码能够处理多次调用。例如:如果您销毁onDataChanged
中的进度对话框而不是隐藏它,那么您也需要检查它的存在。