Pass information from a selected item in the list to EditText

1
Hello, I'm having problems when I select a client in a ListView , I have to pass its name to an EditText of the other Activity and pass the address too.

But when I select the Client it is grouping the Name with the Address in the same line. And I have another problem with toString, how to pass all the data in the table without me NullPointer or appear NULL values.

Following codes:

{       

    /**
     * Método de listagem dos clientes
     */
    public List<Cliente> listarClientes() {

        // List que recebe os dados que são percorridos no while
        List<Cliente> listaClientes = new ArrayList<Cliente>();
        // Variável para utilizar a query no Cursor
        String sql = "select * from dj_tb_cli";
        // Objeto que recebe os registros do Banco de Dados
        Cursor cursor = getReadableDatabase().rawQuery(sql, null);

        try {
            // Percorre todos os registros do cursor
            while (cursor.moveToNext()) {
                Cliente cliente = new Cliente();
                // Carrega os atributos do Banco de Dados
                cliente.setId(cursor.getLong(0));
                cliente.setNomeCliente(cursor.getString(1));
                cliente.setEnderecoCliente(cursor.getString(6));

                listaClientes.add(cliente);

                Log.i(TAG, "Listando Clientes");
            }
        } catch (Exception e) {
            Log.i(TAG, e.getMessage());
        } finally {
            // Garante o fechamento do Banco de Dados
            cursor.close();
        }
        return listaClientes;
    }
}

My ListView.

public class ListaClientesBD extends ListActivity implements OnItemClickListener {

    private String clienteSel;
    private String endSel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        DatabasesDAO db = new DatabasesDAO(this);

        setListAdapter(new ArrayAdapter<Cliente>(this,
                android.R.layout.simple_list_item_1, db.listarClientes()));
        ListView listView = getListView();
        listView.setOnItemClickListener(this);
    }

    // private List<String> listarClientes() {
    // return Arrays.asList("Cliente 1", "Cliente 2", "Cliente 3");
    // }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {

        TextView textView = (TextView) view;

        String mensagem = "Cliente Selecionado: " + textView.getText();

        Toast.makeText(getApplicationContext(), mensagem, Toast.LENGTH_SHORT)
                .show();
        // startActivity(new Intent(this, NovoPedidoActivity.class));

        Intent intent = new Intent(ListaClientesBD.this,
                TelaNovoPedidoActivity.class);

        clienteSel = ((TextView) view).getText().toString();
        intent.putExtra("cliente", clienteSel.toString());

        endSel = ((TextView) view).getText().toString();
        intent.putExtra("endCliente", endSel.toString());

        startActivity(intent);
}

This section is in my Activity. It receives the values by the key of the selected item in the list.

    nomeCliente = (EditText) findViewById(R.id.nmClienteBD);
    String parametroCli = getIntent().getStringExtra("cliente");
    nomeCliente.setText(parametroCli);

    enderecoCliente = (EditText) findViewById(R.id.endClienteBD);
    String parametroEndCli = getIntent().getStringExtra("endCliente");
    enderecoCliente.setText(parametroEndCli);

    EditText nomeProduto = (EditText) findViewById(R.id.produtoBD);
    String parametroProd = getIntent().getStringExtra("nmProd");
    nomeProduto.setText(parametroProd);
    
asked by anonymous 17.04.2014 / 20:32

2 answers

2

Boy, it is not advisable to work with ArrayList of Objects to mount listViews on android. To run smooth and more stable, it is best to use HashMaps for Strings with key value.

As for your project, specifically, you are using android.R.layout.simple_list_item_1 to mount your listview, a layout that has only 1 textview, and then you use this same textview to setar the contact and the address, so it's all coming together, do you understand?

I would advise you to do the following ... Mount your HashMap, from your cursor, and create your own adapter to assemble the list.

HashMap array populated by cursor

    ArrayList<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
    HashMap map = new HashMap<String, String>();

    map.put("chaveNome",cursor.getString(1));
    map.put("chaveEndereco", cursor.getString(6));

    fillMaps.add(map);

    ExemploAdapter adapter = new ExemploAdapter(this, fillMaps);
    lv.setAdapter(adapter);

Layout pro item from your list - R.layout.list_item

   <?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearlayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            style="@style/TextViewSize"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:text="TextView"
            android:textColor="#fff" />

        <TextView
            android:id="@+id/textView2"
            style="@style/TextViewMinimumSize"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:text="TextView"
            android:textColor="#fff" />
    </LinearLayout>

Structure of your Adapter

public class ExemploAdapter extends BaseAdapter{

private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;

public ExemploAdapter(Activity activity, ArrayList<HashMap<String, String>> data) {
    this.activity = activity;
    this.data = data;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    return data.size();
}

@Override
public Object getItem(int position) {
    //retorna seu objeto    
    return data.get(position);
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    //monta o layout de cada item da sua lista
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.list_item, null);

    TextView nome = (TextView)vi.findViewById(R.id.textView1);
    TextView endereco = (TextView)vi.findViewById(R.id.textView2);

    HashMap<String, String> list = new HashMap<String, String>();
    list = data.get(position);

    nome.setText(list.get("chaveNome"));
    endereco.setText(list.get("chaveEndereco"));

    return vi;
}

}

And in the click, just run for a hug;)

lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> adapter, View v, int position,final long id) {
            Object obj = adapter.getItemAtPosition(position);
        }
    });

I think you can understand it :) Good luck!

    
17.04.2014 / 22:00
1

Good morning,

Well, let's see if I understand you're wanting to get the value of an EditText within a given item from a ListView right?

Well if this is wrong, the ideal would be to work with the array of objects that are in your adapter that would be a List, in it you would extract the item you want and proceed from there, anyway you should do something asism:

In the public void onItemClick(AdapterView<?> parent, View view, int position, long id) method, use the position parameter with the getItem(int arg0) method, it returns the Client and with it you can pick up the desired client and fetch the information.

I can not test where I am from, but it looks something like this:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {

    Cliente cliente =  (Cliente) getListAdapter().getItem(position);

    //Continue daqui
}
    
17.04.2014 / 20:51