Updating values in a Listview

Asked

Viewed 2,488 times

3

I add the values that are within 3 arrays in the hashMap to insert into the listview:

 ArrayList<HashMap<String, String>> lista = new ArrayList<HashMap<String,String>>();

    for(int i=0; i<tema.length; i++ ) {
        HashMap<String,String> item = new HashMap<String,String>();
        item.put("tema", tema[i]+": "+tempo[i]);
        item.put("palavras", palavras[i]);
        lista.add(item);
    }

What I want to do is that when the user clicks the button SUBIR, for example. The item in position 2 (if that’s what he clicked on) rises to position 1, and the item in position 1 takes position 2.

Replacing:

 up.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        if(posicao!=0 && tema.length>1) {

              auxtema = tema[posicao-1];
              auxpalavras = palavras[posicao-1];
              auxtempo = tempo[posicao-1];

              tema[posicao-1] = tema[posicao];
              palavras[posicao-1] = palavras[posicao];
              tempo[posicao-1] = tempo[posicao];

              tema[posicao] = auxtema;
              palavras[posicao] = auxpalavras;
              tempo[posicao] = auxtempo;


        }

Inside the array I was able to do. I replaced it, but how do I update it inside the listview, and update it?

2 answers

2

I’m not sure I understand your doubt, but in your case listview have a Adapter you can implement a method that updates the ArrayList within the Adapter and calls the method notifyDataSetChanged

Ex.:

public void atualizarLista(ArrayList<HashMap<String, String>> lista) {
    this.lista = lista;
    notifyDataSetChanged();
}

2


As your code is not showing how you urged the Listview can’t be sure if you’re using a adapter standard or your own adapter. Assuming you’ve implemented your own Listadapter (inheriting directly or indirectly from Basedapter) or used some adapter capable of handling dynamic updates (e. g., Arrayadapter), the solution is to call the method notifyDataSetChanged after updating the model:

To do this (assuming that listView is your ListView)

((BaseAdapter) listView.getAdapter()).notifyDataSetChanged();

Updating: By the structure of your code you must be using a Simpleadapter.

If my answer and @R3olon’s did not make sense I strongly recommend to read the tutorial Lars Vogel: Using lists in Android (in English).

  • I don’t have enough data on your code/Adapter to give you a specific solution, but remove the item of ArrayList and call notifyDataSetChanged should work. Take a look in that SOE response.

Browser other questions tagged

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