Pass information from a selected item in the list to Edittext

Asked

Viewed 3,071 times

1

Hello, I’m in trouble when I select a client in a Listview, I have to pass his name to a Edittext of the other Activity and pass the address also.

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

Follows 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 snippet 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);

2 answers

2

Boy, it is not advised to work with Object Arraylist to mount listViews on android. To run smoother and more stable, the most suitable is to use String Hashmaps with value key.

As for your project, specifically, you’re using the android.R.layout.simple_list_item_1 to assemble your listview, a layout that has only 1 textview, and then you use this same textview to set the contact and address, why it’s all coming together, 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 Arraylist, 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);

Pro layout of your list item - 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 the hug ;)

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

I think I understand :) Good luck!

  • I was away for a while, I’ll take a look and tell you if it worked.. I got into some problems here in the development that got stuck..

1

Good morning,

Good let’s see if I understand you are wanting to get the value of an Edittext within a certain item of a ListView right?

Well if that is quite mistaken, the ideal would be to work with the array of objects that is in your Adapter that would be a List, in it you would extract the item you want and proceed from there, finally you should do something asism:

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

I can’t test where I’m from, but it’s something like this:

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

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

    //Continue daqui
}
  • In my code I pass the client parameter to be presented in Edittext. When it appears it is grouping the Client with Address. And in my toString when I give append with other information there that mixes everything. Would you have something to exemplify in code? I have little time in Android development.

  • @user2362558, added my answer, see if it suits you.

  • I understood what you meant.. But still, I’m struggling here. There are many things that are still new to me. For example for me to get the name and address, how do I pass the position? this holiday promises to be long to study all these things.rs

  • @user2362558, you need to implement the onItemClick method, in it one of the parameters is the "position" you use to take the position and reach the desired value in the Array that is on Adapter. Feel free to ask whatever you want, but I suggest you rephrase your question and add whatever you have doubt, so I’ll answer it better

  • Okay, I’m going to elaborate here a description of my doubts about that for you.

Browser other questions tagged

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