简体   繁体   English

从 RecyclerView 中删除未使用的项目

[英]Removing unused item from RecyclerView

I want to show the hospitals near me and also in firestore.So I gave condition that if the hospital near to me within radius of 1 km are equal to those hospital in my firestore data will show in the RecyclerView.我想显示我附近的医院以及消防站中的医院。所以我给出的条件是,如果我附近的医院在 1 公里半径内等于我的消防站数据中的那些医院,将显示在 RecyclerView 中。 Its working that its showing as per condition but if their is four hospital near me and among those One is in my firestore then its showing one hospital name and also showing other three items in RecyclerView as blank which is not in the firestore.它的工作原理是根据情况显示,但如果他们是我附近的四家医院,其中一家在我的消防站中,那么它会显示一个医院名称,并且在 RecyclerView 中的其他三个项目也显示为空白,这不在消防站中。

Code of RecyclerView Adapter RecyclerView 适配器代码

public class HospitalAdapter extends RecyclerView.Adapter<HospitalAdapter.MyViewHolder> {
        ArrayList<HospitalData> hospitalDataList;
        Context context;
        private int lastPosition = -1;
        private FirebaseFirestore fStore;
    
        public HospitalAdapter(ArrayList<HospitalData> hospitalDataList, Context context) {
            this.hospitalDataList = hospitalDataList;
            this.context = context;
        }
    
        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View itemView = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.hospital_list_view, viewGroup, false);
    
            return new MyViewHolder(itemView);
    
        }
    
    
        @Override
        public void onBindViewHolder(final MyViewHolder viewHolder, final int i) {
            final HospitalData data = hospitalDataList.get(i);
    
            fStore= FirebaseFirestore.getInstance();
            Query query=fStore.collection("Hospital");
            query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if(task.isSuccessful()){
                        for(QueryDocumentSnapshot queryDocumentSnapshot: Objects.requireNonNull(task.getResult())){
                            if(queryDocumentSnapshot.getString("Name").equals(data.hospitalName)){
    
                                viewHolder.name.setText(data.hospitalName);
                                viewHolder.distance.setText(data.distance + " Km");
                                viewHolder.rating.setText(data.rating);
    
                                setAnimation(viewHolder.parent, i);
                                viewHolder.parent.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        Intent intent = new Intent(context, HospitalDepartment.class);
                                        intent.putExtra("hospitalName", data.hospitalName);
                                        intent.putExtra("Latitude",String.valueOf(data.lat));
                                        intent.putExtra("Longitude",String.valueOf(data.lon));
                                        context.startActivity(intent);
                                    }
                                });
    
                            }
                        }
                    }
                }
            });
    
    
    
        }
    
        private void setAnimation(View viewToAnimate, int position) {
            // If the bound view wasn't previously displayed on screen, it's animated
            if (position > lastPosition) {
                Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
                viewToAnimate.startAnimation(animation);
                lastPosition = position;
            }
        }
    
        @Override
        public int getItemCount() {
            return hospitalDataList.size();
        }
    
        static class MyViewHolder extends RecyclerView.ViewHolder {
            TextView name, distance, rating;
            ConstraintLayout parent;
    
            public MyViewHolder(View itemView) {
                super(itemView);
                parent = itemView.findViewById(R.id.parent);
                name = itemView.findViewById(R.id.hName);
                distance = itemView.findViewById(R.id.hDistance);
                rating = itemView.findViewById(R.id.hRating);
            }
        }

Screen Shots屏幕截图

The item count of a recycler view is determined by the getItemCount() method.回收站视图的项目计数由getItemCount()方法确定。 So, to solve your problem, the simplest I can think of is have a member variable that holds the size of the recycler view in your adapter class.因此,为了解决您的问题,我能想到的最简单的方法是在适配器 class 中拥有一个保存回收器视图大小的成员变量。 And return that in getItemCount() method.并在getItemCount()方法中返回。 Now you are going to update this size member variable in your onComplete() method according to the size of the result list received.现在您将根据收到的结果列表的大小在onComplete()方法中更新这个大小成员变量。 After that, call notifyDataSetChanged() to update your recycler view accordingly.之后,调用notifyDataSetChanged()以相应地更新您的回收站视图。

Now while this may solve your problem, I think you do not have any need to pass the ArrayList with all hospital data to your adapter since you are not displaying all of them anyway.现在虽然这可能会解决您的问题,但我认为您无需将带有所有医院数据的 ArrayList 传递给您的适配器,因为您无论如何都不会显示所有这些数据。 I would suggest you to move the fetch operation of FireStore data to your activity.我建议您将 FireStore 数据的获取操作移动到您的活动中。 So fetch the data, compare it with your all HospitalData list and create another List having only the Hospitals that match and feed this particular List to your recycler view.因此,获取数据,将其与您的所有 HospitalData 列表进行比较,并创建另一个列表,其中仅包含匹配的医院并将此特定列表提供给您的回收站视图。

Don't fetch Hospitals list every time on BindViewHolder , it is a bad practice, instead fetch the hospitals from firestore and filter the data prior to setting data to adapter like below不要每次都在BindViewHolder上获取Hospitals列表,这是一种不好的做法,而是从firestore获取hospitals并在将数据设置为适配器之前过滤数据,如下所示

    ArrayList<HospitalData> hospitalDataList = new ArrayList<>();//fill this with local data
    Query query=fStore.collection("Hospital");
    query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
       @Override
       public void onComplete(@NonNull Task<QuerySnapshot> task) {
           if(task.isSuccessful()){
              ArrayList<QueryDocumentSnapshot> fireStoreData = task.getResult();
               for(HospitalData data: hospitalDataList){
                   for(QueryDocumentSnapshot fireData: fireStoreData){
                         if(queryDocumentSnapshot.getString("Name").equals(list.get(finalI1).name)){
                                HospitalData data = new HospitalData(list.get(finalI1).name, numberFormat.format(distanceKilometer), list.get(finalI1).rating.toString() + "/5.0", true,list.get(finalI1).latitude,list.get(finalI1).longitude);
                                hospitalDataList.add(data);
                         }
                    }
               }
               hospitalAdapter.notifyDataSetChanged();
           }
       }               
  });

in hospital_list_view.xml setVisibility to GONE to parent layout在 hospital_list_view.xml setVisibility to GONE to parent layout

    RecyclerView recyclerView = findViewById(R.id.recycler_view);
            HospitalAdapter hospitalAdapter = new HospitalAdapter((ArrayList<HospitalData>) hospitalDataList, HospitalListActivity.this);
            RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
            recyclerView.setLayoutManager(manager);
            recyclerView.setAdapter(hospitalAdapter);   
    
    
     fStore= FirebaseFirestore.getInstance();
                    Query query=fStore.collection("Hospital");
                    final int finalI1 = i;
                    query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<QuerySnapshot> task) {
                            if(task.isSuccessful()){
                                for(QueryDocumentSnapshot queryDocumentSnapshot: Objects.requireNonNull(task.getResult())){
                                    if(queryDocumentSnapshot.getString("Name").equals(list.get(finalI1).name)){
                                        HospitalData data = new HospitalData(list.get(finalI1).name, numberFormat.format(distanceKilometer), list.get(finalI1).rating.toString() + "/5.0", true,list.get(finalI1).latitude,list.get(finalI1).longitude);
                                        hospitalDataList.add(data);
        
                                    }
                                }
                            }
                        }
                    });
hospitalAdapter.notifyDataSetChanged();

Problem is in hospitalDataList.add(data);问题出在hospitalDataList.add(data); not storing data and sending to adapter.Inside the condition if(queryDocumentSnapshot.getString("Name").equals(list.get(finalI1).name)) when I printing list.get(finalI1).name) in log then its printing corectly but problem is not storing data and sending to adapter.不存储数据并发送到适配器。当我在日志中打印list.get(finalI1).name)时,在条件if(queryDocumentSnapshot.getString("Name").equals(list.get(finalI1).name))内,然后它正确打印,但问题是不存储数据并发送到适配器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM