How to delete selected items from a listiview

1

I have been trying for days to delete the elements that I have selected in a Listview by means of checkboxs without success. Only achieve the total elimination of the list. Here goes my code:

item_agenda.java

public class Item_agenda {
private String nombre;
private String nombre_contacto;
private String nombre_facebook;
private String nombre_instagram;
private String nombre_twitter;
boolean checked = false;

public Item_agenda() {
    super();
}

/////////////////////////////////////////////////////////////////
public String getNombre() {
    return nombre;
}

public void setNombre(String nombre) {
    this.nombre = nombre;
}

////////////////////////////////////////////////////////////////
public String getNombre_contacto() {
    return nombre_contacto;
}

public void setNombre_contacto(String nombre_contacto) {
    this.nombre_contacto = nombre_contacto;
}
/////////////////////////////////////////////////////////////////

public String getNombre_facebook(){
    return nombre_facebook;
}

public void setNombre_facebook(String nombre_facebook){
    this.nombre_facebook = nombre_facebook;
}

////////////////////////////////////////////////////////////////

public String getNombre_instagram(){
    return nombre_instagram;
}

public void setNombre_instagram(String nombre_instagram){
    this.nombre_instagram = nombre_instagram;
}

////////////////////////////////////////////////////////////////

public String getNombre_twitter(){
    return nombre_twitter;
}

public void setNombre_twitter(String nombre_twitter){
    this.nombre_twitter = nombre_twitter;
}


public boolean isChecked(){
    return checked;
}

}

Adapter_agenda.java

public class Adapter_agenda extends BaseAdapter{

protected Activity activity;
protected List<Item_agenda> items;


//CONSTRUCTOR
public Adapter_agenda(Activity activity, List<Item_agenda> items) {
    this.activity = activity;
    this.items = items;
}

private class ViewHolder {
    private TextView text;
    private CheckBox check;

}

//Cuenta los elementos
@Override
public int getCount() {
    return items.size();
}
//Devuelve un objeto de una determinada posicion
@Override
public Object getItem(int position) {
    return items.get(position);
}

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

public boolean isChecked(int position) {
    return items.get(position).checked;
}


//METODO PRINCIPAL, AQUI SE LLENAN LOS DATOS
@Override
public View getView(final int position, View convertView, ViewGroup parent) 
{
    View rowView = convertView;
    ViewHolder viewHolder = new ViewHolder();

    if (rowView == null) {
        LayoutInflater inflater = (activity).getLayoutInflater();
        rowView = inflater.inflate(R.layout.item_agenda, null);
        viewHolder.text = (TextView) rowView.findViewById(R.id.nombre_agenda);
        viewHolder.check = (CheckBox) rowView.findViewById(R.id.checkbox);
        rowView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) rowView.getTag();
    }

    viewHolder.text.setText(items.get(position).getNombre());
    viewHolder.check.setChecked(items.get(position).checked);




    final String itemStr = items.get(position).getNombre();
    viewHolder.text.setText(itemStr);

    viewHolder.check.setTag(position);



    viewHolder.check.setChecked(isChecked(position));

//Devolvemos vista
    return rowView;
}

}

// Function of the MainActivty that performs the only complete deletion

public void eliminar_todo(){
    eliminar.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            AlertDialog.Builder dialogo1 = new AlertDialog.Builder(ConstruyeAgenda.this);
            dialogo1.setTitle("Importante");
            dialogo1.setMessage("¿ Esta seguro que desea eliminar este usuario ?");
            dialogo1.setCancelable(false);
            dialogo1.setPositiveButton("Confirmar", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogo1, int id) {
                    lista.clear();
                    adaptador.notifyDataSetChanged();
                    Intent intent = new Intent(ConstruyeAgenda.this, Vincular.class);
                    startActivity(intent);
                }
            });
            dialogo1.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogo1, int id) {
                    Intent intent = new Intent(ConstruyeAgenda.this, Vincular.class);
                    startActivity(intent);
                }
            });
            dialogo1.show();

        }
    });
}
    
asked by flo 07.09.2017 в 21:21
source

3 answers

0

You have to send to remove the element either by its index or by the object as such:

ArrayList.remove(índice);

or

ArrayList.remove(elemento);

Then you have the adapter notify you of the changes:

Adapter.notifyDataSetChanged();

Clarification : This code works for me in Android Studio, I do not know if it works the same in other IDE's.

    
answered by 07.09.2017 в 22:03
-1

Look, I do not know how your code is to select the items, but you can solve your problem in the following way.

Create an ArrayList of type int in which you store the positions of the items you select. Then in the onClick event of the delete button you go through that ArrayList and delete the items that are in the positions that were stored in the ArrayList.

You declare the ArrayList as a variable of the class

ArrayList<int> posiciones = new ArrayList<int>();

Store the positions of the items you will remove

// ...
// Dentro del código que utilizas para seleccionar los items.
posiciones.add(posicion)
//...

In the onClick event of the delete button

public void eliminar_todo(){
    eliminar.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            AlertDialog.Builder dialogo1 = new AlertDialog.Builder(ConstruyeAgenda.this);
            dialogo1.setTitle("Importante");
            dialogo1.setMessage("¿ Esta seguro que desea eliminar este usuario ?");
            dialogo1.setCancelable(false);
            dialogo1.setPositiveButton("Confirmar", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogo1, int id) {

                    // Eliminas los items que se encuentran en las
                    // posiciones almacenadas en el ArrayList
                    for(int posicion : posiciones) {

                        lista.remove(posicion)
                    }

                    adaptador.notifyDataSetChanged();
                    Intent intent = new Intent(ConstruyeAgenda.this, Vincular.class);
                    startActivity(intent);
                }
            });
            dialogo1.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogo1, int id) {
                    Intent intent = new Intent(ConstruyeAgenda.this, Vincular.class);
                    startActivity(intent);
                }
            });
            dialogo1.show();

        }
    });
}
    
answered by 08.09.2017 в 02:10
-1

You are deleting all the elements since you are removing all the elements from the list by clicking on the "Confirm" button in the dialog:

 dialogo1.setPositiveButton("Confirmar", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogo1, int id) {
                    //Elimina todos los elementos del List.
                    lista.clear();
                    //Actualiza datos en Adapter.
                    adaptador.notifyDataSetChanged();
                    Intent intent = new Intent(ConstruyeAgenda.this, Vincular.class);
                    startActivity(intent);
                }
            });

To delete only the selected items , as you have on each object item_agenda has the property:

public boolean isChecked(){
    return checked;
}

you can get the values, if true is removed from the list, when you finish updating your adapter:

    dialogo1.setPositiveButton("Confirmar", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogo1, int id) {

                        //Elimina elementos seleccionados del List.
                        int counter = 0;
                        for(Boolean item : items){
                          if(item) { //true, elimina de la lista.
                            lista.remove(counter);
                          }
                          counter++;
                        }

                        //Actualiza datos en Adapter.
                        adaptador.notifyDataSetChanged();

                        Intent intent = new Intent(ConstruyeAgenda.this, Vincular.class);
                        startActivity(intent);
                    }
                });
    
answered by 08.09.2017 в 00:16