RecyclerView 正在复制项目可能的解决方案是啥?

Posted

技术标签:

【中文标题】RecyclerView 正在复制项目可能的解决方案是啥?【英文标题】:RecyclerView is duplicating items What might be possible solution?RecyclerView 正在复制项目可能的解决方案是什么? 【发布时间】:2021-12-20 12:21:01 【问题描述】:
RecyclerView r1;
LocationCallback callback;
Location location;
FusedLocationProviderClient client;
public String name, car, number;
ArrayList<MyModel> list = new ArrayList<>();
Boolean flag = false;
@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_recycler);
    r1 = findViewById(R.id.r1);
    client = LocationServices.getFusedLocationProviderClient(this);
    callback = new LocationCallback() 
        @Override
        public void onLocationResult(@NonNull LocationResult locationResult) 
            super.onLocationResult(locationResult);
            if (locationResult == null) 
                return;
            
            location = locationResult.getLastLocation();

            getdriver();

            Toast.makeText(Recycler.this, "Location is:" + location.getLongitude() + location.getLatitude(), Toast.LENGTH_SHORT).show();
        
    ;
    showupadatelocation();

private void showupadatelocation() 
    LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) 
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(4000)
                .setFastestInterval(3000);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        
        client.requestLocationUpdates(locationRequest, callback, Looper.myLooper());
     else 
        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
    

MyAdapter myAdapter;
private void getdriver() 
    DatabaseReference driver = FirebaseDatabase.getInstance().getReference().child("Drivers Available");
    GeoFire geoFire = new GeoFire(driver);
    GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(location.getLatitude(), location.getLongitude()), 100);
    geoQuery.removeAllListeners();
    geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() 
        @Override
        public void onKeyEntered(String key, GeoLocation location) 
            DatabaseReference reff = FirebaseDatabase.getInstance().getReference().child("Users").child("Drivers").child(key);
            reff.addValueEventListener(new ValueEventListener() 
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) 
                    if (snapshot.exists()) 
                        flag = true;
                        Map<String, Object> map = (Map<String, Object>) snapshot.getValue();
                        if (map.get("Name") != null) 
                            name = map.get("Name").toString();
                        
                        if (map.get("Number") != null) 
                            number = map.get("Number").toString();
                        
                        if (map.get("Car") != null) 
                            car = map.get("Car").toString();
                        
                        list.add(new MyModel(name,number,car));
                        /*
                        int count=list.size();
                        int count1=myAdapter.getItemCount();
                        if(count==count1)
                            list.add(new MyModel(name,number,car));
                            flag=true;
                        
                    Toast.makeText(Recycler.this, "list size"+count, Toast.LENGTH_SHORT).show();
                    Toast.makeText(Recycler.this, "Adapter size"+count1, Toast.LENGTH_SHORT).show();

                         */
                    
                
                @Override
                public void onCancelled(@NonNull DatabaseError error) 
                
            );
        
        @Override
        public void onKeyExited(String key) 

        
        @Override
        public void onKeyMoved(String key, GeoLocation location) 

        
        @Override
        public void onGeoQueryReady() 

        
        @Override
        public void onGeoQueryError(DatabaseError error) 

        
    );
    myAdapter = new MyAdapter(list, Recycler.this);
    r1.setAdapter(myAdapter);
    r1.setLayoutManager(new LinearLayoutManager(Recycler.this));

@Override
public void onBackPressed() 
    super.onBackPressed();
    list.clear();
    client.removeLocationUpdates(callback);

这是我的适配器:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.viewholder> 
ArrayList <MyModel> list;
Context context;
public MyAdapter(ArrayList<MyModel> list, Context context) 
    this.list = list;
    this.context = context;


@NonNull
@Override
public viewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 
    View view= LayoutInflater.from(context).inflate(R.layout.driverinfo,parent,false);
    return new viewholder(view);


@Override
public void onBindViewHolder(@NonNull viewholder holder, int position) 
    MyModel myModel=list.get(position);
    holder.t1.setText(myModel.getName());
    holder.t2.setText(myModel.getNumber());
    holder.t3.setText(myModel.getCar());


@Override
public int getItemCount() 
    return list.size();

public class viewholder extends RecyclerView.ViewHolder
    TextView t1,t2,t3;
    public viewholder(@NonNull View itemView) 
        super(itemView);
        t1=itemView.findViewById(R.id.namber);
        t2=itemView.findViewById(R.id.naame);
        t3=itemView.findViewById(R.id.caar);
    

这是 RecyclerView 中的重复数据虽然我的 firebase 数据库中只有 2 个详细信息

This is the structure of my database

And this is what my problem is the recycler view keeps on adding data in an infinite loop what might be the condition for stopping this to happen ?

【问题讨论】:

你试过stable Ids吗? 在添加新数据之前是否尝试过清除列表? @Zain 我没试过稳定的身份证是什么,你能详细说明一下吗? 它为每个 recyclerView 项目提供一个唯一的 id,以确保不会显示具有相同 id 的重复项目 @AlexMamo 是的,我尝试在添加新细节之前清除列表,但我遇到了一些不相关的问题,因为每当我的数据库中有 2 个数据时,列表大小就会增加一倍,例如数据 2,大小为 4 我不知道为什么会这样,否则我有一个逻辑来停止数据的重复,但也许我不是在开始时而是在代码中间清除数据,我会尝试清除程序开头的列表,如果可行,会通知您! 【参考方案1】:

试试这个

geoQuery.getCache().clear();

【讨论】:

说明没有这样的函数geoQuery.getCache().clear();它在 getCache() 中显示错误

以上是关于RecyclerView 正在复制项目可能的解决方案是啥?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 recyclerview 滚动时调用 api? [复制]

如何点击Activity中的recyclerview项目? [复制]

如何使用不同类型的项目制作 RecyclerView? [复制]

如何从 recyclerview 和 sqlite 中删除项目? [复制]

RecyclerView smoothScroll位于中心位置。安卓

XML/android:如何为 RecyclerView 项目制作白色下划线? [复制]