Android - Capturar parametro de un elemento cliqueado de un listview

 
Vista:
sin imagen de perfil

Capturar parametro de un elemento cliqueado de un listview

Publicado por Bruno (2 intervenciones) el 27/10/2016 13:29:19
Hola muy buenas a todos, estoy desarrollando una App y se me presenta el siguiente inconveniente el cual no e podido solucionar. espero y puedan ayudarme o al menos encaminarme.

Yo recibo desde una base MYSQL y a través de JSON información la cual rellena un Listview, cuando hago clic en un elemento determinado de la lista, muestro un AlertDialog el cual me da dos opciones:

- Confirmar: captura el id almacenado en dicho JSON y lo envía como parámetro (mediante una clase httpHandler), para realizar acciones en la base de datos.

-Cancelar: solo devuelve la actividad.
mi problema es que no logro capturar el elemento cliqueado, sino que siempre recibo el ultimo elemento.


en mi proyecto tengo Una clase muestradatos.class y otra Pacientes.class, las cuales contienen lo siguiente:

Pacientes.class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
public class Pacientes {
    private String especialidad;
    private String fecha;
    private String hora;
    private String lugar;
    private String id_turno;
 
 
    public Pacientes(String especialidad, String fecha, String hora, String lugar, String id_turno) {
        super();
        this.especialidad = especialidad;
        this.fecha = fecha;
        this.hora = hora;
        this.lugar = lugar;
        this.id_turno = id_turno;
 
    }
 
    //Especialidad
    public String getEspecialidad(){
        return especialidad;
    }
    public void setEspecialidad(String especialidad){
        this.especialidad = especialidad;
    }
 
    //Fecha
    public String getFecha(){
        return fecha;
    }
    public void setFecha(String fecha){
        this.fecha = fecha;
    }
 
    //Hora
    public String getHora(){
        return hora;
    }
    public void setHora(String hora){
        this.hora = hora;
    }
 
 
    //Lugar
    public String getLugar(){
        return lugar;
    }
    public void setLugar(String lugar){
        this.lugar = lugar;
    }
 
    //ID Turno
    public String getId_turno(){
        return id_turno;
    }
 
    public void setId_turno(String id_turno) {
        this.id_turno = id_turno;
    }
 
 
    public String toString(){
        return this.especialidad+"\n" +this.fecha+"\n"+this.hora+"\n"+this.lugar+"\n"+this.id_turno;
    }
}

muestradatos.class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
public class muestradatos extends Activity {
 
     //Declaracion Objetos
     private TextView muestra_estado, id_ta;
     private ListView listJson;
 
     String id_tr, id_rs; //Variable Global ID
 
 
 
     @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_muestradatos);
 
 
         //Asignacion de Identificadores (Casting)
         listJson = (ListView)findViewById(R.id.listJson);
 
         muestra_estado = (TextView) findViewById(R.id.estado);
         id_ta = (TextView) findViewById(R.id.id);
 
         //Tarea Hilo 2
         Tarea1 tarea1 = new Tarea1();
         tarea1.cargarContenido(getApplicationContext());
         tarea1.execute(listJson);
 
         //Direcciones Web
         final String url_verificar = "http://192.168.20.123:8099/android/acciones.php";
 
         //Capturar Click ListView
         listJson.setOnItemClickListener(new AdapterView.OnItemClickListener() {
             @Override
             public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
 
                 AlertDialog.Builder builder = new AlertDialog.Builder(muestradatos.this);
                 builder
                         .setTitle("¿Asistirá?")
                         .setCancelable(false)
 
                         .setNegativeButton("Cancelar Turno",
                                 new DialogInterface.OnClickListener() {
                                     public void onClick(DialogInterface dialog, int id) {
                                         dialog.cancel();
 
                                         AlertDialog.Builder builder = new AlertDialog.Builder(muestradatos.this);
                                         builder
                                                 .setTitle("¿Esta Seguro?")
                                                 .setMessage("Recuerde que si cancela el turno debera asistir al Centro de salud para solicitarlo nuevamente")
                                                 .setCancelable(false)
                                                 .setPositiveButton("Si",
                                                         new DialogInterface.OnClickListener() {
                                                             public void onClick(DialogInterface dialog, int id) {
                                                                 dialog.cancel();
                                                                 Toast.makeText(getBaseContext(),"Turno cancelado con exito.",Toast.LENGTH_SHORT).show();
                                                                 muestra_estado.setText("2"); //Asigno estado a una variable
                                                                 //Respuesta desde PHP )
                                                                 httpHandler estado_turno = new httpHandler();
                                                                 String v_id = estado_turno.post(url_verificar);
                                                                 muestra_estado.setText(v_id);
 
 
                                                                 //  finish();
                                                              //   startActivity(getIntent());
                                                             }
                                                         })
 
                                                 .setNegativeButton("No",
                                                         new DialogInterface.OnClickListener() {
                                                             public void onClick(DialogInterface dialog, int id) {
                                                                 dialog.cancel();
                                                             }
                                                         });
 
                                         AlertDialog alert = builder.create();
                                         alert.show();
                                     }
                                 })
 
                         .setPositiveButton("Confirmar Turno",
                                 new DialogInterface.OnClickListener() {
                                     public void onClick(DialogInterface dialog, int id) {
 
                                         dialog.cancel();
                                         Toast.makeText(getBaseContext(),"Turno confirmado con exito.",Toast.LENGTH_SHORT).show();
                                         muestra_estado.setText("1");//Asigno estado a una variable
                                         httpHandler estado_turno = new httpHandler();
                                         String v_id = estado_turno.post(url_verificar);
 
                                         muestra_estado.setText(v_id); //esto solo lo uso para ver lo que envio 
                                         id_ta.setText(id_tr);
                                         //finish();
                                        // startActivity(getIntent());
 
                                     }
                                 });
 
                 AlertDialog alert = builder.create();
                 alert.show();
             }
         });
     }
 
 
      class Tarea1 extends AsyncTask<ListView, Void, ArrayAdapter<Pacientes>>{
        Context contexto;
        ListView list;
        InputStream is;
        ArrayList<Pacientes> listaPacientes = new ArrayList<Pacientes>();
 
          final String numdni = getIntent().getStringExtra("numdni");
          final String pass = getIntent().getStringExtra("pass");
          final String URL = "http://192.168.20.123:8099/android/detallesturnos.php?dni="+numdni+"&pass="+pass;
 
 
        public void cargarContenido(Context contexto){
            this.contexto = contexto;
        }
 
        @Override
        protected void onPreExecute(){
            //Todo Auto-Generated metod stub
        }
 
 
        @Override
        public ArrayAdapter<Pacientes> doInBackground(ListView... params) {
            list = params[0];
            String resultado = "falla";
            Pacientes pac;
 
 
 
            //Creo Conexion HTTP
            HttpClient pacientes = new DefaultHttpClient();
            HttpGet peticionGet = new HttpGet(URL);
 
            try {
                //Obtengo Respuesta
                HttpResponse response = pacientes.execute(peticionGet);
                HttpEntity contenido = response.getEntity();
                is = contenido.getContent();
 
            } catch (ClientProtocolException e) {
                //Todo Auto-Generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                //Todo Auto-Generated metod stub
                e.printStackTrace();
            }
 
            BufferedReader buferlector = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String linea = null;
 
            try {
                while ((linea = buferlector.readLine())!= null) {
                    sb.append(linea);
                }
            } catch (IOException e) {
                //Todo Auto-Generated metod stub
                e.printStackTrace();
            }
            try {
                is.close();
            } catch (IOException e) {
                //Todo Auto-Generated metod stub
                e.printStackTrace();
            }
            resultado = sb.toString();
 
 
            try {
                JSONArray arrayJson = new JSONArray(resultado);
 
                    for (int i = 0; i < arrayJson.length(); i++) {
                        JSONObject objetoJson = arrayJson.getJSONObject(i);
                        pac = new Pacientes(objetoJson.getString("especialidad"), objetoJson.getString("fecha"), objetoJson.getString("hora"), objetoJson.getString("lugar"),objetoJson.getString("id_turno"));
                        listaPacientes.add(pac);
 
                        id_tr = objetoJson.getString("id_turno");
 
                    }
            } catch (JSONException e) {
                //Todo Auto-Generated catch block
                e.printStackTrace();
            }
 
            ArrayAdapter<Pacientes> adaptador = new ArrayAdapter<Pacientes>(contexto, android.R.layout.simple_list_item_1, listaPacientes);
            return adaptador;
 
            }
 
 
 
          @Override
        protected void onPostExecute(ArrayAdapter<Pacientes> result){
            list.setAdapter(result);
 
 
        }
 
        @Override
        protected void onProgressUpdate(Void... values){
        }
 
 
    }
 
 
     public class httpHandler {
 
         final String numdni = getIntent().getStringExtra("numdni"); //Dni Recibido desde Main
 
         public String post(String posturl){
             try{
                 HttpClient httpclient = new DefaultHttpClient();
            /*Creo El objeto HttpClient que nos permite conectarnos mediante peticiones http*/
                 HttpPost httppost=new HttpPost(posturl);
            /*El objeto HttpPost permite que enviemos una peticion de tipo POST a una URL especificada*/
                 //Añadir Parametros
                 List<NameValuePair> params = new ArrayList<NameValuePair>();
                 params.add(new BasicNameValuePair("id_turno",id_tr));
                 params.add(new BasicNameValuePair("dni", numdni ));
                 params.add(new BasicNameValuePair("accion",muestra_estado.getText().toString()));
            /*Una vez añadidos los parametros actualizamos la entidad de httppost, esto quiere decir en pocas palabras anexamos
            los parametros al objeto para que al enviarse al servidor envien los datos que hemos añadido*/
                 httppost.setEntity(new UrlEncodedFormEntity(params));
 
            /*Finalmente ejecutamos enviando la info al server*/
                 HttpResponse resp = httpclient.execute(httppost);
                 HttpEntity ent = resp.getEntity();
 
                 String textResponse = EntityUtils.toString(ent);
                 return textResponse;
             }
             catch(Exception e) { return "error";}
         }
     }


Solo estoy capturando en id_tr = objetoJson.getString("id_turno"); y ese es mi error. pero no se como asignarle el id correspondiente al clic.

desde ya muy agradecido!.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder