Pass variable when clicking on a listView item to another activity [duplicated]

1

Good morning. I have this query because I am too new programming in Android Studio and I do not know where to go. I have a listView that I load with data from a database that I have on my PC and I obtain the data by a php file. That's ok, the list shows it to me. What I need is to be able to click on an iten in the listView and take me to another activity where I can capture the ID of the record to which I'm clicking. The list is added as follows:

public ArrayList<String> obtDatosJSON(String response){
    ArrayList<String> listado = new ArrayList<String>();
    try{
        JSONArray jsonArray = new JSONArray(response);
        String texto;
        for (int i = 0; i < jsonArray.length();i++){

            texto = "\n" +
                    "Barrio: " + jsonArray.getJSONObject(i).getString("barrio") +"\n"+
                    "Dirección: " + jsonArray.getJSONObject(i).getString("direccion") +"  "+
                    "Piso Depto: " + jsonArray.getJSONObject(i).getString("pisoDepto") +" "+
                    "Cliente: " + jsonArray.getJSONObject(i).getString("cliente") +"\n"+
                    "Telefono: " + jsonArray.getJSONObject(i).getString("telefono") + "\n" +
                    "Estado: " + jsonArray.getJSONObject(i).getString("estado") + "\n" +
                    "Cadete Asignado: " + jsonArray.getJSONObject(i).getString("cadete") + "\n";
            listado.add(texto);
        }
    }catch(Exception e){
        e.printStackTrace();
    }
    return listado;
}

Then I made that when I clicked on an item it took me to another Activity:

public void CargarLista(ArrayList<String> datos){
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,datos);
    listado.setAdapter(adapter);
    listado.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        public void onItemClick(AdapterView<?> parent, View view, int position, long id){
            Intent intent = new Intent(view.getContext(),Detalle.class);
            intent.putExtra("ID","");
            startActivity(intent);
        }
    });
}

What I do not know is how to pass the ID of the record, there I saw that it goes in the intent.putExtra. Here's where I do not know what to do: Is it okay to create a variable with the JSON data?

String Idetalle = jsonArray.getJSONObject(i).getString("id");

But dsp that variable does not let me call it or I do not know how to do it inside the intent.putExtra.

Do they guide me more or less how to achieve what I need?

It would even be useful if they see it and they tell me that everything is wrong from the beginning so I would look for another way to do it.

    
asked by Juan 22.05.2017 в 05:20
source

3 answers

3

Your code is well on track. One way to achieve this is to use the adapter to which you pass the data. For example, assuming that "data" contains the ids you want to pass:

public void onItemClick(AdapterView<?> parent, View view, int position, long id){
            Intent intent = new Intent(view.getContext(),Detalle.class);
            intent.putExtra("ID",datos.get(position);
            startActivity(intent);
        }

In the next activity you only need to pick up the extra. For example:

Bundle bundle = getIntent().getExtras();
String id = bundle.get("ID");

If you want to pass more data to the next activity I recommend that you create a custom adapter, it is done by creating a class that extends, for example, to BaseAdapter.

    
answered by 22.05.2017 / 09:50
source
1

Responding to the following question:

The best thing is that you create and implement an own adapter, which allows you to manage more data independently, and in these cases I usually create from the json an array for each type of data and I pass them to an adapter of this style:

public class UnidadAdapter extends BaseAdapter {

    private Context context;
    private LayoutInflater layoutInflater;
    private List<String> id,barrio,direccion,...;

    public UnidadAdapter(Context context1,
                         List<String> id1,
                         List<String> barrio1,
                         List<String> direccion1,
                         ...) {
        context = context1;
        id = id1;
        barrio = barrio1;
        ....

        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

    @Override
    public Object getItem(int i) {
        return id.get(i);
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View mView = layoutInflater.inflate(R.layout.listunidad,viewGroup,false);
/*Esto me permite darle formato en un layotu propio*/
        TextView tv_id_unidad = (TextView) mView.findViewById(R.id.tv_id_unidad);
        tv_id_unidad.setText(id.get(i));
        ...
        return mView;
    }

And then I put the adapter in the class.

final UnidadAdapter unidadAdapter = new UnidadAdapter(this,id, ....);
        listView.setAdapter(unidadAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                intent = new Intent(view.getContext(),Reservas.class);
                intent.putExtra("ID",id.get(i));            


                startActivity(intent);
            }
        });

It is going a step further, but you will see that it is much more versatile. Go ahead and try.

    
answered by 24.05.2017 в 18:01
0

Carmen I ask you to take me one last doubt:  With which you passed me the data I capture them and I show them in another class:

Bundle bundle = getIntent().getExtras();
String id = (String) extras.get("ID");
textView = (TextView) findViewById(R.id.textView);
textView .setText(id);

And what happened with all this:

public void CargarLista(final ArrayList<String> datos){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,datos);
listado.setAdapter(adapter);
listado.setOnItemClickListener(new AdapterView.OnItemClickListener(){
    public void onItemClick(AdapterView<?> parent, View view, int position, long id){
        Intent intent = new Intent(view.getContext(),Detalle.class);
        intent.putExtra("ID", datos.get(position));
        startActivity(intent);
    }
});
}

public ArrayList<String> obtDatosJSON(String response){
ArrayList<String> listado = new ArrayList<String>();
try{
    JSONArray jsonArray = new JSONArray(response);
    String texto;
    for (int i = 0; i < jsonArray.length();i++){
        texto = "\n" +
                "Id: " + jsonArray.getJSONObject(i).getString("id") +"\n"+
                "Barrio: " + jsonArray.getJSONObject(i).getString("barrio") +"\n"+
                "Dirección: " + jsonArray.getJSONObject(i).getString("direccion") +"  "+
                "Piso Depto: " + jsonArray.getJSONObject(i).getString("pisoDepto") +" "+
                "Cliente: " + jsonArray.getJSONObject(i).getString("cliente") +"\n"+
                "Telefono: " + jsonArray.getJSONObject(i).getString("telefono") + "\n" +
                "Estado: " + jsonArray.getJSONObject(i).getString("estado") + "\n" +
                "Cadete Asignado: " + jsonArray.getJSONObject(i).getString("cadete") + "\n";
        listado.add(texto);
    }
}catch(Exception e){
    e.printStackTrace();
}
return listado;
}

What I need is not to show all the data, just show me the ID because my final intention is to save that ID in a request to pass it to my PHP file and put it in a query (In the where):

RequestParams parametros = new RequestParams();
parametros.put("IdPedido", id)

How could I just pass the Id and not all the data? Is it necessary to change the structure of what I already did?

    
answered by 22.05.2017 в 17:06