Refresh Listview

Asked

Viewed 2,177 times

0

When I click on my Listview, I open a dialog with 3 buttons (Edit, Delete and Return). By clicking delete, I would like to have Listview updated. At what point I must do this?

public class Relacao_cliente extends Activity {

private static final Comum c1 = new Comum();
private final ListView ListViewR_Cliente = (ListView) findViewById(R.id.lvRelacao_Cliente);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_relacao_cliente);

    Populate_ListView();


}

@Override
public void onResume(){
    super.onResume();
    BaseAdapter adapter = (BaseAdapter) ListViewR_Cliente.getAdapter();
    adapter.notifyDataSetChanged();
}

public void Populate_ListView()
{

    try {
        ClienteDAO BD = new ClienteDAO(this);
        //LISTA DE CLIENTES GERADA PELO MÉTODO LISTAR_CLIENTES()
        ArrayList<Cliente> Lista_Clientes =  BD.Listar_Clientes();

        if(!Lista_Clientes.isEmpty())
        {
            //SE A LISTA NÃO ESTIVER VAZIA, ENTÃO EU SETO MEU ADAPTER.
            ListViewR_Cliente.setAdapter(new ClienteAdapter(this, Lista_Clientes,ListViewR_Cliente));

        }else{

            //c1.Exibir_Mensagem(this, "Não existe nenhum cliente cadastrado!");
        }

    } catch (Exception e) {
        c1.Exibir_Mensagem(this, e.getMessage().toString());
    }
}


}

Adapter:

public class ClienteAdapter extends BaseAdapter  {
static TabHost tabHost;

private Context context;
private ArrayList<Cliente> list;
private ListView MyListView;


public ClienteAdapter(Context context, ArrayList<Cliente> list, ListView lv){
    this.context = context;
    this.list = list;
    this.MyListView = lv;
}

@Override
public int getCount() {

    return list.size();
}

@Override
public Object getItem(int position) {
    //list.get(position);
    return  list.get(position);
}

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


@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final Cliente cCliente = list.get(position);
    View layout;
    final Comum c1 = new Comum();

    if(convertView == null){
        LayoutInflater inflater = (LayoutInflater)   context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        layout  = inflater.inflate(R.layout.itens_relacao_cliente, null);
    }else
    {
        layout = convertView;
    }


    //Campos da minha list view pré definida.
    TextView Nome = (TextView) layout.findViewById(R.id.lblNome);
    Nome.setText(cCliente.getNome());

    TextView Apelido = (TextView) layout.findViewById(R.id.lblApelido);
    Apelido.setText("Apelido: " + cCliente.getApelido());

    //MyListView.setClickable(true);
    MyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
     public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
        Cliente C = (Cliente) list.get(position);

         Dialog_Info_Cli d1 = new Dialog_Info_Cli();
         d1.Exibir_Info_Cliente(context, C);

    }
    }); 

    return layout;
}




}

Dialogue:

public class Dialog_Info_Cli {
private AlertDialog alerta;
final Comum c1 = new Comum();

public void Exibir_Info_Cliente(final Context context, String Titulo,final Cliente C) {


    LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.layout_info_cli, null); 

    TextView Nome = (TextView) view.findViewById(R.id.lblNome);
    Nome.setText(C.getNome());

    TextView Fone = (TextView) view.findViewById(R.id.lblTelefone);
    Fone.setText("Fone: (" + C.getDDD() + ")" + C.getCelular() );

    TextView Apelido = (TextView) view.findViewById(R.id.lblApelido);
    Apelido.setText("Apelido: (" + C.getApelido()+ ")");

    TextView Obs = (TextView) view.findViewById(R.id.lblValor_Obs);
    Obs.setText("" + C.getObservacao());


     view.findViewById(R.id.btnEditar).setOnClickListener(new View.OnClickListener() { 
        public void onClick(View arg0) { 

            Intent intent = new Intent(context, Cadastro_cliente.class);
            intent.putExtra("Cliente", C);
            context.startActivity(intent);
            alerta.dismiss(); 
        } 
    }); 


    view.findViewById(R.id.btnExcluir).setOnClickListener(new View.OnClickListener() {
         public void onClick(View v)
         {
             AlertDialog.Builder alert = new AlertDialog.Builder(context);
             alert.setMessage("Deseja excluir o cliente?");

            alert.setPositiveButton("SIM", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                ClienteDAO db = new ClienteDAO(context);
                try {
                    db.Deletar_Cliente(C);
                    c1.Exibir_Mensagem(context, "Registro Excluido com sucesso!");
                    alerta.dismiss(); 
                } catch (Exception e) {
                    c1.Exibir_Mensagem(context, "Erro ao excluir cliente!");
                }


              }
            });

            alert.setNegativeButton("NÃO", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int whichButton) {
                 dialog.dismiss();
              }
            });

            alert.show();

         } });


        view.findViewById(R.id.btnHome).setOnClickListener(new View.OnClickListener() { 
            public void onClick(View arg0) { 
                alerta.dismiss(); 
            } 
        }); 

        AlertDialog.Builder builder = new AlertDialog.Builder(context); 
        builder.setTitle("Informações do Cliente"); 
        builder.setView(view); 
        alerta = builder.create(); 
        alerta.show(); 
    }
}
  • If deleted successfully you update the ListView.

  • Place the delete code

1 answer

2


Soon after deleting the data from the local Torage, you update your view, but for that you must be sure that the data was deleted from the Torage. To update your view you can do in a few ways, I’ll show you the simplest.

  1. You can repopulate your ListView on Activity, calling again Populate_ListView(). It works, but it is not the best method because you will waste processing by reloading your entire list. If it’s a large list of complex items it can slow down the app.
  2. You can delete your item directly from your ListView, using the following methods:

    listView.removeViewAt(adapter.getPosition(C)); // C o seu objeto do tipo Cliente
    

or:

    listView.removeView(child); // child é um objeto do tipo View criado pelo seu adapter

or:

    adapter.remove(C); // C o seu objeto do tipo Cliente
    // utilizar ListView.setAdapter(adapter); para recarregar o adapter caso seja necessario 

I think the first option will solve your problem. Since the dialog is in a different class, you can use an interface to callback and delete your item from Listview.

Browser other questions tagged

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