我刚开始使用Firestore。所以我尝试将我的数据直接拟合到recyclerview中,这是我用来参考的code。 这是我的UserRecyclerView片段:
public class UserRecyclerView extends Fragment{
private ArrayList<User> user;
RecyclerView mRecyclerView;
public UserRecyclerView(){}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recycler_view,container,false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
FirestoreRecyclerAdapter adapter = getFirestoreRecyclerAdapter();
mRecyclerView.setAdapter(adapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
@NonNull
private FirestoreRecyclerAdapter getFirestoreRecyclerAdapter() {
Query query = FirebaseFirestore.getInstance()
.collection("users");
FirestoreRecyclerOptions<User> options = new FirestoreRecyclerOptions.Builder<User>()
.setQuery(query, User.class).build();
return new FirestoreRecyclerAdapter<User, UserViewHolder>(options) {
@Override
protected void onBindViewHolder(UserViewHolder holder, int position, User model) {
Log.d("USER", "DATA: "+model.getName());
holder.BindView(position, model);
}
@Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_list, parent, false);
return new UserViewHolder(view);
}
};
}
private class UserViewHolder extends RecyclerView.ViewHolder{
TextView info;
UserViewHolder(View itemView) {
super(itemView);
info = (TextView) itemView.findViewById(R.id.info_text);
}
void BindView(int position, User model){
info.setText(model.getName()+" , "+model.getId());
}
}
除了启动上面的片段之外,我的MainActivity中没有任何内容。我不知道我的代码有什么问题。它显示没有错误,当我运行应用程序时它不会崩溃。它只是进入recyclerview布局,我通过放置textview字段进行检查以确定(现在已删除)。我希望你帮我解决问题。这可能是因为适配器?帮帮我搞清楚我还上传了我的数据库片段。 提前致谢!
答案 0 :(得分:2)
确保在适配器上调用startListening
以启动与Cloud Firestore的连接,否则将不会加载任何数据。
@Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
@Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
答案 1 :(得分:0)
创建如下所示的recyclerview:
FirestoreRecyclerAdapter adapter = getFirestoreRecyclerAdapter();
//add below line
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(adapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));