Search code examples
androidlistviewcheckboxandroid-recyclerviewlistviewitem

Android Listview item, when I implement setCheck(true) in any checkbox some item changed randomly


this is my first post, and I have a doubt about a listview item management, I have seen some post about recycleView, but I don´t understand yet how to implement it in my problem.

Well, I've got a listView that shows some elements like a shopping car where the user clicks the button autorizarDetalleSolicitud, which opens an alertDialog where an user choices a wished amount of that respective item, so if the amount is bigger than zero, the checkbox changes to state TRUE, but when I test this function, I could see that other checkBoxes are activated (or changes to state TRUE) randomly; i.e. When I input an amount to first item, the state of penultimate checkBox changes to TRUE. Thanks for your attention.

//Button of each listview item
public void autorizarDetalleSolicitud(View v) {


    LinearLayout layoutboton = (LinearLayout) v.getParent();
    checkBoxelemento = (CheckBox) layoutboton.getChildAt(0);

    RelativeLayout relativeLayout = (RelativeLayout) layoutboton.getParent();
    TableLayout tableLayout = (TableLayout) relativeLayout.getChildAt(1);
    TextView tipoelementotextview = (TextView) tableLayout.findViewById(R.id.tipoelem);
    TextView unidadelem = (TextView) tableLayout.findViewById(R.id.unidadelem);
    TextView idelem = (TextView) tableLayout.findViewById(R.id.idelem);
    TextView cantpedida = (TextView) tableLayout.findViewById(R.id.cantidadelem);
    cantautorizadatextview = (TextView) tableLayout.findViewById(R.id.cantautorizado);
    final String tipoelemento = tipoelementotextview.getText().toString();

    cantidadpedida = Double.parseDouble(cantpedida.getText().toString());
    cantidadautorizada = Double.parseDouble(cantautorizadatextview.getText().toString());
    idelemento = idelem.getText().toString();

    // configura el alert dialog
    builder = new AlertDialog.Builder(this);
    builder.setMessage(unidadelem.getText() + " a autorizar:");
    builder.setNegativeButton(R.string.cancelar, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
        }
    });

    if (tipoelemento.equals("Material")) {
        numberPickerCantidad = new NumberPicker(getApplicationContext());
        numberPickerCantidad.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
        numberPickerCantidad.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);


        String[] nums = new String[100];
        for (int i = 0; i < nums.length; i++) {
            nums[i] = Integer.toString(i);
        }
        numberPickerCantidad.setMinValue(0);
        numberPickerCantidad.setMaxValue(nums.length - 1);
        numberPickerCantidad.setWrapSelectorWheel(false);
        numberPickerCantidad.setDisplayedValues(nums);
        if(cantidadautorizada==0){
            numberPickerCantidad.setValue(cantidadpedida.intValue());
        }else{
            numberPickerCantidad.setValue(cantidadautorizada.intValue());
        }

        builder.setPositiveButton(R.string.agregar, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                int cantidadautorizada = numberPickerCantidad.getValue();
                autorizarCantidad((double)cantidadautorizada,tipoelemento);
            }
        });
        builder.setView(numberPickerCantidad);

    } else {
        cantreactivosoli = new EditText(getApplicationContext());
        cantreactivosoli.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        cantreactivosoli.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});
        cantreactivosoli.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));

        if(cantidadautorizada==0){
            cantreactivosoli.setText(cantidadpedida + "");
        }else{
            cantreactivosoli.setText(cantidadautorizada + "");
        }

        cantreactivosoli.setText(cantidadpedida + "");
        builder.setView(cantreactivosoli);
        builder.setPositiveButton(R.string.aceptar, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                String cantidadedittext = cantreactivosoli.getText().toString();
                if (!cantidadedittext.equals("")) {
                    Double cantidadingresada = Double.parseDouble(cantidadedittext);
                    autorizarCantidad(cantidadingresada,tipoelemento);
                } else {
                    Toast toast = Toast.makeText(getApplicationContext(), R.string.error_sincantidad, Toast.LENGTH_SHORT);
                    toast.show();
                }
            }
        });
        builder.setView(cantreactivosoli);
    }

    builder.show();
}

// Method that saves the input value in an arraylist and implements a setCheck(true) of that itemstrong text
public void autorizarCantidad(Double cantidadingresada, String tipoelemento){

    if (cantidadingresada <= cantidadpedida) {
        int flag = 0;
        for (int indice = 0; indice < elementosrevisados.size(); indice++) {
            if (elementosrevisados.get(indice).getId().equals(idelemento)) {
                elementosrevisados.get(indice).setCantidadAutorizada(cantidadingresada+"");
                if (tipoelemento.equals("Material")) {
                    cantautorizadatextview.setText(cantidadingresada.intValue()+"");
                }else{
                    cantautorizadatextview.setText(cantidadingresada+"");
                }
                cantidadpedida = cantidadingresada;
                flag=1;
                break;
            }
        }

        if(flag==0) {
            Elemento elem = new Elemento(idelemento, cantidadpedida + "", cantidadingresada + "");
            elementosrevisados.add(elem);
            checkBoxelemento.setChecked(true);
            if (tipoelemento.equals("Material")) {
                cantautorizadatextview.setText(cantidadingresada.intValue()+"");
            }else{
                cantautorizadatextview.setText(cantidadingresada+"");
            }
        }

        for(int i=0;i<elementosrevisados.size();i++){
            Log.e("Elemento revisado: ",elementosrevisados.get(i).toString());
        }
    } else {
        Toast toast = Toast.makeText(getApplicationContext(), R.string.error_cantidadautorizada, Toast.LENGTH_SHORT);
        toast.show();
    }

}

Solution

  • SOLUTION!

    To solve my problem, I based on this answer recording an array with positions of the checkboxes verifying if they were checked, I mean, this a boolean array, and each checkbox has a status TRUE or FALSE. Thanks to @AnshulTyagi

        public class ElementoAdapter extends BaseAdapter {
    
        private ArrayList<Boolean> status = new ArrayList<Boolean>();
        private static LayoutInflater inflater = null;
        private ArrayList<HashMap<String, String>> data;
        Activity activity;
    
        CompoundButton.OnCheckedChangeListener miCheckedListener = new CompoundButton.OnCheckedChangeListener() {
    
            @Override
            public void onCheckedChanged(CompoundButton checkBoxView,boolean isChecked){
    
                int posicioncheck = (Integer)checkBoxView.getTag();
    
                if (checkBoxView.isChecked()) {
    
                    status.set(posicioncheck,true);
    
                } else {
    
                    status.set(posicioncheck,false);
                }
            }
        };
    
        public ElementoAdapter(Activity activity, ArrayList<HashMap<String, String>> data){
            this.activity = activity;
            this.data = data;
            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            for (int i = 0; i < data.size(); i++) {
                status.add(false);
            }
        }
    
    
        @Override
        public int getCount() {
            return data.size();
        }
    
        @Override
        public Object getItem(int position) {
            return position;
        }
    
        @Override
        public long getItemId(int position) {
            return position;
        }
    
        @Override
        public View getView (int position, View convertView, ViewGroup parent) {
            View vista = convertView;
            ViewHolder holder;
            if (vista == null) {
                vista =  inflater.inflate(R.layout.listitem_elemento,null);
                holder = new ViewHolder();
                holder.labelIdElemento = (TextView) vista.findViewById(R.id.labelIdElemento);
                holder.idElemento = (TextView)  vista.findViewById(R.id.idelem);
                holder.labelTipo = (TextView) vista.findViewById(R.id.labelTipoElemento);
                holder.tipoElemento = (TextView) vista.findViewById(R.id.tipoelem);
                holder.labelCodigoElemento = (TextView) vista.findViewById(R.id.labelCodigo);
                holder.codigoElemento = (TextView) vista.findViewById(R.id.codigoelem);
                holder.labelDescripcionElemento= (TextView) vista.findViewById(R.id.labelDescripcion);
                holder.descripcionElemento = (TextView) vista.findViewById(R.id.descripcionelem);
                holder.labelMarcaElemento = (TextView) vista.findViewById(R.id.labelMarca);
                holder.marcaElemento = (TextView) vista.findViewById(R.id.marcaelem);
                holder.labelUnidadMedida = (TextView) vista.findViewById(R.id.labelUnidadMedida);
                holder.unidadMedida = (TextView) vista.findViewById(R.id.unidadelem);
                holder.checkBoxElemento = (CheckBox) vista.findViewById(R.id.checkBox);
                holder.botonElemento = (Button) vista.findViewById(R.id.botonsolic);
    
                vista.setTag(holder);
    
            } else {
                holder = (ViewHolder) convertView.getTag();
                // remove the listener so that it does not get attached to other chechboxes.
                holder.checkBoxElemento.setOnCheckedChangeListener(null);
                holder.checkBoxElemento.setChecked(status.get(position));
                Log.e("check "+position,status.get(position)+"");
    
            }
    
            holder.idElemento.setText(data.get(position).get("idelemento"));
            holder.tipoElemento.setText(data.get(position).get("tipoelemento"));
            holder.codigoElemento.setText(data.get(position).get("codigoelemento"));
            holder.descripcionElemento.setText(data.get(position).get("descripcionelemento"));
            holder.marcaElemento.setText(data.get(position).get("marcaelemento"));
            holder.unidadMedida.setText(data.get(position).get("unidadmedida"));
            Log.e("idelemento creado ",data.get(position).get("idelemento"));
            holder.checkBoxElemento.setTag(position);
    
    
    
    //add a custom listener
            holder.checkBoxElemento.setOnCheckedChangeListener(miCheckedListener);
    
            return vista;
        }
    
        static class ViewHolder {
            TextView labelIdElemento;
            TextView idElemento;
            TextView labelTipo;
            TextView tipoElemento;
            TextView labelCodigoElemento;
            TextView codigoElemento;
            TextView labelDescripcionElemento;
            TextView descripcionElemento;
            TextView labelMarcaElemento;
            TextView marcaElemento;
            TextView labelUnidadMedida;
            TextView unidadMedida;
            CheckBox checkBoxElemento;
            Button botonElemento;
        }
    
    }