Listview update does not work

Asked

Viewed 185 times

0

Hello,

Can help?

On the search screen is returning the data from the previous research plus the new research performed. Listview does not update only with new search return results.

I’ve used the

listView.setAdapter(null);

adapter=new SimpleAdapter(EnderecosActivity.this, enderecotList,
                R.layout.list_end,
                new String[] { }, new int[] {});
        listView.setAdapter(adapter);

Follows code below:

package com.example.wander.cadastro;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.test.suitebuilder.TestMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cepBr.model.Cep;
import cepBr.service.CepServiceAndroid;

public class EnderecosActivity extends AppCompatActivity {
TextView username;
String cepRetornado;
String logradouroRetornado;
String bairroRetornado;
String localidadeRetornada;
String estadoRetornado;

EditText logradouro;
EditText localidade;
EditText estado;

Bundle bundle;
private ListView listView;
ArrayList<HashMap<String, String>> enderecotList;
ListAdapter adapter;
CepServiceAndroid cepServiceAndroid= new CepServiceAndroid();
List<Cep> resultados;
String user=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_enderecos);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Intent intent=getIntent();
    bundle = intent.getExtras();

    user = bundle.getString("username");
    setUser(user);
    enderecotList=new ArrayList<>();
    listView= (ListView) findViewById(R.id.list_enderecos);


    Button btn= (Button) findViewById(R.id.buttonPesquisar);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            estado= (EditText) findViewById(R.id.editTextUf);
            localidade= (EditText) findViewById(R.id.editTextLocalidade);
            logradouro= (EditText) findViewById(R.id.editTextLogradouro);
            String state= estado.getText().toString();
            String city=localidade.getText().toString();
            String place=logradouro.getText().toString();

            getParametros(state,city,place);


            limparForm();
        }
    });

    rediretcView(toolbar);
}



private void rediretcView(Toolbar toolbar) {
    toolbar.setOnMenuItemClickListener(item -> {
        switch(item.getItemId()){
            case R.id.menu_endereco:
                bundle.putString("username", user);
                recreate();
                return true;

            case R.id.menu_perfil:
                Intent perfil= new Intent(this, UsuarioDetalheActivity.class);
                bundle.putString("username", user);
                perfil.putExtras(bundle);
                startActivity(perfil);
                return true;
        }
        return false;
    });
}

public void validateParams(String state,String city, String place){
    if (state.trim().isEmpty() || city.trim().isEmpty()|| place.trim().isEmpty()){
        Toast.makeText(this, "Todos os campos são obrigatórios", Toast.LENGTH_SHORT).show();
    }
}

public void getParametros(String state, String city, String place){
    enderecotList=new ArrayList<>();
    //  if(adapter!=null){
    enderecotList.clear();

    adapter=new SimpleAdapter(EnderecosActivity.this, enderecotList,
            R.layout.list_end,
            new String[] { }, new int[] {});
    listView.setAdapter(adapter);
    // }
    validateParams(state,city,place);
    EnderecosHelper enderecosHelper=new EnderecosHelper();
    enderecosHelper.execute(state,city,place);

}

public void limparForm(){
    estado.setText("");
    localidade.setText("");
    logradouro.setText("");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

public void setUser(String user){
    username= (TextView) findViewById(R.id.txtUsername);

    UsuarioDao usuarioDao= new UsuarioDao(this);
    Cursor cursor= usuarioDao.getByEmail(user);
    cursor.moveToFirst();
    String name=cursor.getString(cursor.getColumnIndex(DataSource.USERNAME));
    username.setText(name);

}

private class EnderecosHelper extends AsyncTask<String,CepServiceAndroid,List<Cep>> {


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        int quant=listView.getCount();
        String q= String.valueOf(quant);
        Log.i("QUANTIDADE", q);
        if(quant>0) {
            enderecotList=new ArrayList<>();
            Log.i("LIMPANDO",q);
            //enderecotList.clear();
            listView.setAdapter(null);

        }
    }

    @Override
    protected List<Cep> doInBackground(String... params) {
        try {
            resultados=new ArrayList<Cep>();
            resultados= cepServiceAndroid.requestCeps(params[0],params[1],params[2]);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultados;
    }

    @Override
    protected void onPostExecute(List<Cep> results) {
        HashMap<String, String> endereco = null;



            for (Cep resultado:resultados) {
                if(resultado.getStatus().equals("SUCCESS")) {
                    cepRetornado=resultado.getCep();
                    logradouroRetornado=resultado.getLogradouro();
                    bairroRetornado=resultado.getBairro();
                    localidadeRetornada=resultado.getLocalidade();
                    estadoRetornado=resultado.getUf();

                    endereco = new HashMap<>();
                    endereco.put("cep", cepRetornado);
                    endereco.put("logradouro",logradouroRetornado);
                    endereco.put("bairro", bairroRetornado);
                    endereco.put("localidade", localidadeRetornada);
                    endereco.put("estado", estadoRetornado);

                    enderecotList.add(endereco);
                }
                if (resultado.getStatus().equals("NOT_FOUND")){
                    Toast.makeText(EnderecosActivity.this, "CEP não encontrado", Toast.LENGTH_LONG).show();
                }


        }

        adapter = new SimpleAdapter(EnderecosActivity.this, enderecotList,
                R.layout.list_end,
                new String[] { "cep", "logradouro","bairro", "localidade",
                        "estado"}, new int[] {
                R.id.textCep, R.id.textLogradouro, R.id.textBairro, R.id.textLocalidade,
                R.id.textEstado });

        listView.setAdapter(adapter);


    }


}

}

<?xml version="1.0" encoding="utf-8"?>

    <TextView
        android:id="@+id/txtUsername"
        android:visibility="invisible"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<EditText
    android:id="@+id/editTextUf"
    android:layout_width="131dp"
    android:layout_height="45dp"
    android:ems="10"
    android:inputType="textPersonName"
    android:hint="UF"
    tools:layout_editor_absoluteX="2dp"
    tools:layout_editor_absoluteY="28dp" />

    <EditText
        android:id="@+id/editTextLocalidade"
        android:layout_width="wrap_content"
        android:layout_height="45dp"
        android:layout_weight="0.53"
        android:ems="10"
        android:hint="Localidade"
        android:inputType="textPersonName"
        tools:layout_editor_absoluteX="153dp"
        tools:layout_editor_absoluteY="28dp" />

    <EditText
        android:id="@+id/editTextLogradouro"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:ems="10"
        android:hint="Logradouro"
        android:inputType="textPersonName"
        tools:layout_editor_absoluteX="2dp"
        tools:layout_editor_absoluteY="100dp" />

    <Button
        android:id="@+id/buttonPesquisar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pesquisar"
        tools:layout_editor_absoluteX="2dp"
        tools:layout_editor_absoluteY="160dp" />

    <ListView
        android:id="@+id/list_enderecos"
        android:layout_width="wrap_content"
        android:layout_height="60mm"
        android:layout_weight="2">


    </ListView>

<TextView
    android:id="@+id/textCep"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="2dip"
    android:textColor="@color/colorAccent" />

<TextView
    android:id="@+id/textLogradouro"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="#5d5d5d"
    android:textStyle="bold" />
<TextView
    android:id="@+id/textBairro"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="2dip"
    android:paddingTop="6dip"
    android:textColor="@color/colorPrimaryDark"
    android:textSize="16sp"
    android:textStyle="bold" />
<TextView
    android:id="@+id/textLocalidade"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="2dip"
    android:paddingTop="6dip"
    android:textColor="@color/colorPrimaryDark"
    android:textSize="16sp"
    android:textStyle="bold" />
<TextView
    android:id="@+id/textEstado"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="2dip"
    android:paddingTop="6dip"
    android:textColor="@color/colorPrimaryDark"
    android:textSize="16sp"
    android:textStyle="bold" />

  • You have to use the method adapter.notifyDataSetChanged(); to check if there has been any change in the list.

  • So this function does not compile, nor is it even made available by Intelij. The ones that appear are italic notify() italic and italic notifyAll() italic

  • Searching found a location that informs that it is not possible to implement adapter.notifyDataSetChanged(); directly in this way I customize an Adapter but continues the application of adapter.notifyDataSetChanged(); had no effect.

1 answer

0


try to do it o:

    // ...
    @Override
    protected void onPostExecute(List<Cep> results) {
        HashMap<String, String> endereco = null;
        // ...
    }

    adapter = new SimpleAdapter(EnderecosActivity.this, enderecotList,
        R.layout.list_end,
        new String[] { "cep", "logradouro","bairro", "localidade",
                    "estado"}, new int[] {
        R.id.textCep, R.id.textLogradouro, R.id.textBairro, R.id.textLocalidade,
        R.id.textEstado });
        listView.setAdapter(null); 
        listView.setAdapter(adapter);
    }
}
// ...

or else create your own Adapter where Voce can have greater control over its mechanism.

One thing I didn’t know why, was that: {R.id.textCep, R.id.textLogradouro, R.id.textBairro, R.id.textLocalidade, R.id.textEstado }, that is, in my opinion Voce would have to pass here, the set values of your "map".

If you get in trouble, let us know.

Browser other questions tagged

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