Update data in Listview with Arrayadapter

Asked

Viewed 328 times

1

I have a Listview that will be filled with some different data, which may or may not be called (simultaneously or not).

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

If he 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 I don’t know how to augment what already exists in Adapter and add to Listview. The way it is, it erases what was put on Listview in the first if and just put what comes in the second if.

I’ve searched about notifyDataSetChanged(), but for my case, where I use a custom adapter with extends Arrayadapter, I couldn’t find a solution.

object_add and object_rem are Arraylist < String[ ] >

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.