Android - Posicion de un elemento de un listview

 
Vista:

Posicion de un elemento de un listview

Publicado por javi (1 intervención) el 27/06/2017 19:27:45
Hola buenas, estoy realizando el tfg sobre una aplicacion android y he quedado atascado, tengo un listview que recoge datos de una base de datos, el problema es que no se como recoger la posicion al pulsar en uno de los elementos de la lista para saber que elemento se ha seleccionado:

Mi codigo principal:

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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
package com.dam.profesor.serviciosweb;
 
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener,AdapterView.OnItemClickListener {
 
 
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
 
    }
    public void pulsao(View v){
 
        Intent intent = new Intent(MainActivity.this, Pago.class);
        startActivity(intent);
    }
    Context context;
    Button consultar;
    ListView lista;
    String rdia,rmes,rano,rhora,rminutos;
 
 
 
    //Button consultarporid;
    /*EditText idendificador;
    EditText nombre;
    EditText direccion;
    TextView resultado;
    ImageView imageView;
    */
 
    // IP de mi Url
    String IP = "http://alquilalo.esy.es";
    // Rutas de los Web Services
    String GET = IP + "/obtener_alumnos.php";
    String GET_BY_ID = IP + "/obtener_alumno_por_id_imagen.php";
 
    String IMAGENES = IP + "/imagenes/";
    ObtenerWebService hiloconexion;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
 
        rdia =getIntent().getExtras().getString("rdia");
        rmes =getIntent().getExtras().getString("rmes");
        rano =getIntent().getExtras().getString("rano");
        rhora =getIntent().getExtras().getString("rhora");
        rminutos =getIntent().getExtras().getString("rminutos");
 
        context=this;
 
 
      lista = (ListView) findViewById(R.id.listView1);
 
 
        // Enlaces con elementos visuales del XML
        //resultado = (TextView)findViewById(R.id.resultado);
        consultar = (Button)findViewById(R.id.consultar);
        //consultarporid = (Button)findViewById(R.id.consultarid);
       // idendificador = (EditText)findViewById(R.id.eid);
        //nombre = (EditText)findViewById(R.id.enombre);
        //direccion = (EditText)findViewById(R.id.edireccion);
        //resultado = (TextView)findViewById(R.id.resultado);
        //imageView=(ImageView)findViewById(R.id.imageView);
        // Listener de los botones
 
        consultar.setOnClickListener(this);
       // consultarporid.setOnClickListener(this);
 
 
 
 
 
    }
public Context getContext(){
    return context;
}
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
 
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
 
        return super.onOptionsItemSelected(item);
    }
 
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.consultar:
 
                hiloconexion = new ObtenerWebService();
                hiloconexion.execute(GET,"1");   // Parámetros que recibe doInBackground
 
                break;
 
            default:
 
                break;
        }
    }
 
   /* public int ObtenerLongitudTabla(){
        int longitud=15;
        String cadena ="http://alquilalo.esy.es/obtener_alumnos.php" ;
        URL url = null; // Url de donde queremos obtener información

            try {
                url = new URL(cadena);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //Abrir la conexión
                connection.setRequestProperty("User-Agent", "Mozilla/5.0" +
                        " (Linux; Android 1.5; es-ES) Ejemplo HTTP");
                //connection.setHeader("content-type", "application/json");

                int respuesta = connection.getResponseCode();
                StringBuilder result = new StringBuilder();

                if (respuesta == HttpURLConnection.HTTP_OK) {


                    InputStream in = new BufferedInputStream(connection.getInputStream());  // preparo la cadena de entrada

                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));  // la introduzco en un BufferedReader

                    // El siguiente proceso lo hago porque el JSONOBject necesita un String y tengo
                    // que tranformar el BufferedReader a String. Esto lo hago a traves de un
                    // StringBuilder.

                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);        // Paso toda la entrada al StringBuilder
                    }

                    //Creamos un objeto JSONObject para poder acceder a los atributos (campos) del objeto.
                    JSONObject respuestaJSON = new JSONObject(result.toString());   //Creo un JSONObject a partir del StringBuilder pasado a cadena
                    //Accedemos al vector de resultados

                    JSONArray alumnosJSON = respuestaJSON.getJSONArray("alumnos");   // estado es el nombre del campo en el JSON
                    longitud=alumnosJSON.length();


                    }


                }


             catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

       return longitud;
    }
    */
 
    public class ObtenerWebService extends AsyncTask<String,Void,String>{
        //Bitmap bitmap;
        Bitmap[] bitmap = new Bitmap[15];
        //ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
        Bitmap bitmapotro;
 
 
        ListViewAdapter adapter;
        String[] titulo=new String[15];
 
        String[] plazas=new String[15];
        String[] puertas=new String[15];
        String[] maletas=new String[15];
        String[] aire=new String[15];
        String[] transmision=new String[15];
        String[] precio=new String[15];
 
        @Override
        protected String doInBackground(String... params) {
 
            String cadena = params[0];
            URL url = null; // Url de donde queremos obtener información
            String devuelve ="";
 
 
            if(params[1]=="1") {    // Consulta de todos los alumnos
 
                try {
                    url = new URL(cadena);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //Abrir la conexión
                    connection.setRequestProperty("User-Agent", "Mozilla/5.0" +
                            " (Linux; Android 1.5; es-ES) Ejemplo HTTP");
                    //connection.setHeader("content-type", "application/json");
 
                    int respuesta = connection.getResponseCode();
                    StringBuilder result = new StringBuilder();
 
                    if (respuesta == HttpURLConnection.HTTP_OK) {
 
 
                        InputStream in = new BufferedInputStream(connection.getInputStream());  // preparo la cadena de entrada
 
                        BufferedReader reader = new BufferedReader(new InputStreamReader(in));  // la introduzco en un BufferedReader
 
                        // El siguiente proceso lo hago porque el JSONOBject necesita un String y tengo
                        // que tranformar el BufferedReader a String. Esto lo hago a traves de un
                        // StringBuilder.
 
                        String line;
                        while ((line = reader.readLine()) != null) {
                            result.append(line);        // Paso toda la entrada al StringBuilder
                        }
 
                        //Creamos un objeto JSONObject para poder acceder a los atributos (campos) del objeto.
                        JSONObject respuestaJSON = new JSONObject(result.toString());   //Creo un JSONObject a partir del StringBuilder pasado a cadena
                        //Accedemos al vector de resultados
 
                        String resultJSON = respuestaJSON.getString("estado");   // estado es el nombre del campo en el JSON
 
 
                        if (resultJSON.equals("1")) {     // hay alumnos a mostrar
                            JSONArray alumnosJSON = respuestaJSON.getJSONArray("alumnos");   // estado es el nombre del campo en el JSON
                            for (int i = 0; i < alumnosJSON.length(); i++) {
//se va a poder eliminar el devuelve este de aqui abajo i think
 
                                devuelve = devuelve + alumnosJSON.getJSONObject(i).getString("rutaimagen") + " "  + "\n";
 
                                if (alumnosJSON.getJSONObject(i).getString("rutaimagen").equals("noimagen")) {
                                    bitmap[i] = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
                                    titulo[i]=alumnosJSON.getJSONObject(i).getString("modelo");
 
 
                                    plazas[i]=alumnosJSON.getJSONObject(i).getString("plazas");
                                    puertas[i]=alumnosJSON.getJSONObject(i).getString("puertas");
                                    maletas[i]=alumnosJSON.getJSONObject(i).getString("maletas");
                                    aire[i]=alumnosJSON.getJSONObject(i).getString("aire");
                                   transmision[i]=alumnosJSON.getJSONObject(i).getString("transmision");
                                    precio[i]=alumnosJSON.getJSONObject(i).getString("precio");
 
                                    //bitmapArray.add(bitmap);
 
                                } else {
                                    URL urlimagen = new URL(IMAGENES + alumnosJSON.getJSONObject(i).getString("rutaimagen"));
                                    HttpURLConnection conimagen = (HttpURLConnection) urlimagen.openConnection();
                                    conimagen.connect();
                                    bitmap[i] = BitmapFactory.decodeStream(conimagen.getInputStream());
                                    titulo[i]=alumnosJSON.getJSONObject(i).getString("modelo");
 
                                    plazas[i]=alumnosJSON.getJSONObject(i).getString("plazas");
                                    puertas[i]=alumnosJSON.getJSONObject(i).getString("puertas");
                                    maletas[i]=alumnosJSON.getJSONObject(i).getString("maletas");
                                    aire[i]=alumnosJSON.getJSONObject(i).getString("aire");
                                    transmision[i]=alumnosJSON.getJSONObject(i).getString("transmision");
                                    precio[i]=alumnosJSON.getJSONObject(i).getString("precio");
 
                                    //bitmapArray.add(bitmap);
                                }
 
                            }
 
                        } else if (resultJSON.equals("2")) {
                            devuelve = "No hay alumnos";
                        }
 
 
                    }
 
 
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return devuelve;
            }
 
            return null;
        }
 
        @Override
        protected void onCancelled(String s) {
            super.onCancelled(s);
        }
 
        @Override
        protected void onPostExecute(String s) {
            //resultado.setText(s);
            //for (int i = 0; i < 5; i++) {
            //
            //imageView.setImageBitmap(bitmap);
            //bitmap=bitmapArray.get(0);
            //imageView.setImageBitmap(bitmap[0]);
            //}
            //imageView.setImageBitmap(bitmapotro);
 
            //super.onPostExecute(s);
            Context context = getContext();
            adapter = new ListViewAdapter(context, titulo, bitmap,plazas,puertas,maletas,aire,transmision,precio);
            lista.setAdapter(adapter);
            //lista.setOnItemClickListener(ItemClicked item);
 
 
 
        }
 
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
 
        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
    }
 
}
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
sin imagen de perfil

Posicion de un elemento de un listview

Publicado por Carlos Ismael (38 intervenciones) el 28/06/2017 00:48:37
Hola javi, en el metodo
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

}

con el parametro "int position" puedes obtener la posición en el ListView tengo entendido. puedes crear un Toast para mostrar la posición, al clickear en el elemento.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar