如何在回收器视图中解决重复的数据项



更新位置数据后,我在回收器视图中获得重复的数据项

我尝试过一些类似的方式NotifyDataSetChanged (( 和 setHasStableIds (true(但仍然没有成功

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

}

这是我的适配器

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

FragmentPetaniTerdekat中添加以下方法以检查duplicate条目:

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

在将字符串添加到 lists( nama, jarak, durasi 之前,在 onResponse() 中使用此方法:

        @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 !");
            }
        }

希望这会有所帮助~

相关内容

  • 没有找到相关文章

最新更新