RecyclerView不会显示Firestore查询中的所有项目

时间:2019-08-11 10:52:08

标签: java android firebase android-recyclerview google-cloud-firestore

我进行了一个活动,该活动在RecyclerView中显示用户列表(按名称排序)。而且RecyclerView对于第一个用户来说效果很好,但是从不显示列表的最后一个用户,这很奇怪,因为它应该加载所有数据。

public class UsersRecyclerAdapter extends RecyclerView.Adapter<UsersRecyclerAdapter.ViewHolder> {

    public List<Users> usersList;
    public Context context;

    public UsersRecyclerAdapter(Context context, List<Users> usersList){
        this.usersList = usersList;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_single_layout, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.nameText.setText(usersList.get(position).getName());
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.placeholder(R.drawable.baseline_account_circle_black_24);

        Glide.with(holder.nameText.getContext().getApplicationContext()).applyDefaultRequestOptions(requestOptions).load(usersList.get(position).getImage()).into(holder.profileImage);


        final String user_id = usersList.get(position).userId;

        holder.mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent profileIntent = new Intent(v.getContext(), ProfileActivity.class);
                profileIntent.putExtra("user_id", user_id);
                profileIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(profileIntent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return usersList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        View mView;

        public TextView nameText;
        public CircleImageView profileImage;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            mView = itemView;

            nameText = mView.findViewById(R.id.search_user_name);
            profileImage = mView.findViewById(R.id.search_user_image);



        }
    }

}
public class UsersActivity extends AppCompatActivity {

    private RecyclerView users_list_view;
    private List<Users> users_list;
    private Toolbar mToolbar;

    private FirebaseFirestore firebaseFirestore;
    private FirebaseAuth firebaseAuth;
    private UsersRecyclerAdapter usersRecyclerAdapter;

    private DocumentSnapshot lastVisible;
    private Boolean isFirstPageFirstLoad = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_users);

        mToolbar = findViewById(R.id.new_post_toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle(R.string.all_users);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        users_list = new ArrayList<>();
        users_list_view = findViewById(R.id.users_list_view);

        firebaseAuth = FirebaseAuth.getInstance();

        usersRecyclerAdapter = new UsersRecyclerAdapter(getApplicationContext(), users_list);
        users_list_view.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        users_list_view.setAdapter(usersRecyclerAdapter);
        users_list_view.setHasFixedSize(true);

        if (firebaseAuth.getCurrentUser() != null) {

            firebaseFirestore = FirebaseFirestore.getInstance();

            users_list_view.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);

                    Boolean reachedBottom = !recyclerView.canScrollVertically(1);

                    if (reachedBottom) {

                        loadMorePost();

                    }

                }
            });

            Query firstQuery = firebaseFirestore.collection("Users").orderBy("name", Query.Direction.ASCENDING).limit(3);
            firstQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
                    if (queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty()) {

                        if (isFirstPageFirstLoad) {

                            lastVisible = queryDocumentSnapshots.getDocuments().get(queryDocumentSnapshots.size() - 1);
                            users_list.clear();

                        }

                        for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {

                            if (doc.getType() == DocumentChange.Type.ADDED) {

                                String userId = doc.getDocument().getId();
                                Users user = doc.getDocument().toObject(Users.class).withId(userId);

                                if (isFirstPageFirstLoad) {

                                    users_list.add(user);

                                } else {

                                    users_list.add(0, user);

                                }


                                usersRecyclerAdapter.notifyDataSetChanged();

                            }
                        }

                        isFirstPageFirstLoad = false;
                    }
                }
            });
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }

    private void loadMorePost() {
        if(firebaseAuth.getCurrentUser() != null) {

            Query nextQuery = firebaseFirestore.collection("Users")
                    .orderBy("name", Query.Direction.ASCENDING)
                    .startAfter(lastVisible)
                    .limit(3);

            nextQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
                    if (queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty()) {
                        lastVisible = queryDocumentSnapshots.getDocuments().get(queryDocumentSnapshots.size() - 1);
                        for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {

                            if (doc.getType() == DocumentChange.Type.ADDED) {

                                String userId = doc.getDocument().getId();
                                Users user = doc.getDocument().toObject(Users.class).withId(userId);
                                users_list.add(user);

                                usersRecyclerAdapter.notifyDataSetChanged();
                            }

                        }
                    }
                }
            });

        }

    }
}

我认为Firestore查询存在问题,但我从未见过

非常感谢您的帮助:)

0 个答案:

没有答案