Update data in ListView with ArrayAdapter

1

I have a ListView that will be populated with some different data, which may or may not be called (concurrently or not).

Example: The user can add and remove ingredients from a product. However, it can only remove or only add.

If it does both, the code to treat would be this:

ListView liv = (ListView) findViewById (R.id.lista_sel);
AdaptadorItem adapter;

if (!objetos_add.isEmpty()){
    adater = new AdaptadorItem (contexto, R.layout.item_obs_carrinho, objetos_add);
    liv.setAdapter(adapter);
}

if (!objetos_rem.isEmpty()){
    adater = new AdaptadorItem (contexto, R.layout.item_obs_carrinho, objetos_rem);
    liv.setAdapter(adapter);
}

The problem is that I do not know how to increment what already exists in adapter and add it to ListView .

I have already searched for notifyDataSetChanged () , but for my case where I use a custom adapter with extends ArrayAdapter , I could not find a solution.

ad_objects and red_objects are ArrayList < String [] >

    
asked by anonymous 05.03.2017 / 15:38

1 answer

3

The adapter should only be created once.

ListView liv = (ListView) findViewById (R.id.lista_sel);
AdaptadorItem adapter;
ArrayList<String> objetos = new ArrayList<String>();

adater = new AdaptadorItem (contexto, R.layout.item_obs_carrinho, objetos);

When you want to add / remove items, add / remove them from the ArrayList used when you created the adapter and call the method notifyDataSetChanged()

private void addObjetos(ArrayList<String> objetos_add){
    for(String objeto : objetos_add){
        objetos.add(objeto)
    }
    adapter.notifyDataSetChanged();
}

private void removeObjetos(ArrayList<String> objetos_rem){
    for(String objeto : objetos_rem){
        objetos.remove(objeto)
    }
    adapter.notifyDataSetChanged();
}
    
05.03.2017 / 16:51