Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

java - How to solve duplicate data items in recyclerview

I get duplicate data items in the recyclerview after the location data has been updated

I have tried some such like way NotifyDataSetChanged () and setHasStableIds (true) But still has not succeeded

public class FragmentPetaniTerdekat extends Fragment {

    Context context;
    View view;
    Dialog dialog;
    Session session;
    RecyclerView recyclerView;

    ArrayList<String> nama = new ArrayList<>();
    ArrayList<String> jenis = new ArrayList<>();
    ArrayList<String> jarak = new ArrayList<>();
    ArrayList<String> durasi = new ArrayList<>();

    String my_location;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getContext();
        dialog = new Dialog(context);
        session = new Session(context);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_petani, container, false);
        location();
        return view;
    }

//    get adddres name current location
    private void location() {
        LocationListener mLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // get lat and lng
                if (location != null) {
                    double lat = location.getLatitude();
                    double lng = location.getLongitude();

                    my_location = String.valueOf(lat+","+lng);
                    session.setSession(my_location);
                    getApi(session.getSesssion());
                }else{
                    getApi(session.getSesssion());
                }
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }
        };

        LocationManager mLocationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);

        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), 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 ;
        }

        // check alternative get location
        boolean GPS_ENABLE, NETWORK_ENABLE;
        GPS_ENABLE = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        NETWORK_ENABLE = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (GPS_ENABLE){
            dialog.showDialog("Pesan","memuat data...",true);
            Toast.makeText(getActivity(),"GPS state",Toast.LENGTH_LONG).show();
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 * 5 * 1 , 1, mLocationListener);
        }else if(NETWORK_ENABLE){
            Toast.makeText(getActivity(),"network state",Toast.LENGTH_LONG).show();
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1,mLocationListener);
        }else{
            Toast.makeText(getActivity(),"ganok seng kepilih cak",Toast.LENGTH_LONG).show();
            showSettingsAlert();
        }

    }

//    show alert setting if gps non aktif
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                getActivity().startActivity(intent);
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    public void initRecylerView(View v){
        recyclerView = (RecyclerView)v.findViewById(R.id.recylerview_petani_terdekat);

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(layoutManager);

        RecyclerView.Adapter adapter = new AdapterPetaniTerdekat(context,nama,jarak,durasi);
//        adapter.notifyDataSetChanged();
//        adapter.setHasStableIds(true);
        recyclerView.setAdapter(adapter);

    }

    public void getApi(final String my_location){
        dialog.message("lokasi : "+my_location);
        StringRequest request = new StringRequest(Request.Method.POST, URL_PETANI_TERDEKAT, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response != null) {
                    try {

                        JSONObject get_respone = new JSONObject(response);
                        JSONArray get_result = get_respone.getJSONArray("result_petani_terdekat");

                        for (int i=0; i<get_result.length(); i++){

                            JSONObject result = get_result.getJSONObject(i);

                            ModelPetaniTerdekat petaniTerdekat = new ModelPetaniTerdekat();
                            petaniTerdekat.setNama(result.getString("nama"));

                            JSONObject kriteria = result.getJSONObject("jarak");
                            for (int z=0; z<kriteria.length(); z++){
                                petaniTerdekat.setJarak(kriteria.getString("distance"));
                                petaniTerdekat.setDurasi(kriteria.getString("duration"));
                            }

                            nama.add(petaniTerdekat.getNama());
                            jarak.add(petaniTerdekat.getJarak());
                            durasi.add(petaniTerdekat.getDurasi());

                            dialog.closeDialog();
                        }

                        initRecylerView(view);

                    } catch (JSONException e) {
                        dialog.message("Error : "+e.toString());
                        e.printStackTrace();
                    }
                }else{
                    dialog.message("Error : Tidak ada data !");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                    dialog.message("Error : TimeoutError");
                } else if (error instanceof AuthFailureError) {
                    dialog.message("Error : AuthFailureError");
                } else if (error instanceof ServerError) {
                    dialog.message("Error : ServerError");
                } else if (error instanceof NetworkError) {
                    dialog.message("Error : NetworkError");
                } else if (error instanceof ParseError) {
                    error.printStackTrace();
                    dialog.message("Error : ParseError");
                }
                dialog.closeDialog();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String,String> map = new HashMap<>();
                map.put("lokasi_saya",my_location);
                return map;
            }
        };

        AppSingleton.getInstance(context).addToRequestQueue(request);
        request.setRetryPolicy(new DefaultRetryPolicy(
                60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }


}

and this my adapter

public class AdapterPetaniTerdekat extends RecyclerView.Adapter<AdapterPetaniTerdekat.ViewHolderCabe> {

    Context context;
    ArrayList<String> nama    = new ArrayList<>();
    ArrayList<String> jarak   = new ArrayList<>();
    ArrayList<String> durasi  = new ArrayList<>();

    public AdapterPetaniTerdekat(Context context, ArrayList<String> nama, ArrayList<String> jarak, ArrayList<String> durasi) {
        this.context = context;
        this.nama = nama;
        this.jarak = jarak;
        this.durasi = durasi;
    }

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

    @Override
    public void onBindViewHolder(ViewHolderCabe holder, int position) {
        holder.tv_nama.setText(nama.get(position));
        holder.tv_jarak.setText(jarak.get(position));
        holder.tv_durasi.setText(durasi.get(position));
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

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

    public class ViewHolderCabe extends RecyclerView.ViewHolder{

        TextView tv_nama, tv_jarak, tv_durasi;

        public ViewHolderCabe(View itemView) {
            super(itemView);

            tv_nama = (TextView)itemView.findViewById(R.id.tv_nama_petani);
            tv_jarak = (TextView)itemView.findViewById(R.id.tv_jarak);
            tv_durasi = (TextView)itemView.findViewById(R.id.tv_durasi);

        }

    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add below method in your FragmentPetaniTerdekat to check the duplicate entry:

public boolean isExist(String strNama) {

    for (int i = 0; i < nama.size(); i++) {
        if (nama.get(i).equals(strNama)) {
            return true;
        }
    }

    return false;
}

Use this method inside onResponse(), before adding string into lists(nama, jarak, durasi):

        @Override
        public void onResponse(String response) {
            if (response != null) {
                try {

                    ..............
                    ..................   

                    for (int i = 0; i < get_result.length(); i++){

                        JSONObject result = get_result.getJSONObject(i);

                        ModelPetaniTerdekat petaniTerdekat = new ModelPetaniTerdekat();
                        petaniTerdekat.setNama(result.getString("nama"));

                        JSONObject kriteria = result.getJSONObject("jarak");
                        for (int z=0; z<kriteria.length(); z++){
                            petaniTerdekat.setJarak(kriteria.getString("distance"));
                            petaniTerdekat.setDurasi(kriteria.getString("duration"));
                        }

                        boolean isExist = isExist(petaniTerdekat.getNama());

                        if (!isExist) { // Not exist, Add now
                            nama.add(petaniTerdekat.getNama());
                            jarak.add(petaniTerdekat.getJarak());
                            durasi.add(petaniTerdekat.getDurasi());
                        }

                        dialog.closeDialog();
                    }

                    initRecylerView(view);

                } catch (JSONException e) {
                    dialog.message("Error : "+e.toString());
                    e.printStackTrace();
                }
            }else{
                dialog.message("Error : Tidak ada data !");
            }
        }

Hope this will help~


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...