1
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);
}

Here is my Adapter:

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);
    }
}

Here is the duplication of data in RecyclerView Although i've only 2 details in my firebase database

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 ?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Meet Davda
  • 29
  • 4
  • Have you tried to have [stable Ids](https://stackoverflow.com/questions/54819214/recyclerview-is-duplicating-items/54820003#54820003)? – Zain Nov 07 '21 at 07:09
  • 1
    Have you tried to clear the list before adding new data? – Alex Mamo Nov 07 '21 at 09:31
  • @Zain I've not tried stable Id's what is that can you please elaborate to me in detail? – Meet Davda Nov 07 '21 at 12:36
  • It gives a unique id to each recyclerView item so that it makes sure not to show duplicate items that have the same id – Zain Nov 07 '21 at 12:39
  • @AlexMamo Yes, I tried to clear the list before adding the new details but I was facing some Irrelative Issues in that whenever i was having 2 data in my database the list size was getting double, for example data 2, size was 4 i don't know why was happening that otherwise i had a logic to stop the duplication of data but Maybe i was clearing the data not in the beginning but in middle of the code, I'll try to clear the list in the beginning of the program and will let you know if that works! – Meet Davda Nov 07 '21 at 12:40
  • @Zain oh that's the great idea but where do i have to write that line of code in my program ? – Meet Davda Nov 07 '21 at 12:40

1 Answers1

0

try this

geoQuery.getCache().clear();
Litu
  • 161
  • 1
  • 1
  • 8