Clicking elements of a dynamic ListView obtained from a MYSQL Database

I have a ListView obtained from a MYSQL Database, which shows the list of courses of a teacher, and my idea is when i click on each one, it sends the datas of the course and class through Intents and goes to another activity. The problem is because is a dynamic list and it´s variable the number of rows that have the listview.

For example, the ListView has:

1A 2A 2B

My idea is when i click on 1A, it sends to an another activity passing it 1 and A as variables. When i click on 2A, the variables would be 2 and A and with 2B, 2 and B.

My idea is use the method

public void onItemClick(AdapterView<?> adapterView, View view, int i,
                    long l)

My code is:

 public class Cursos extends MainActivity{
    ListView listaJson;
    String user;
    static int id_usuario;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cursos);

    listaJson = (ListView)findViewById(R.id.lista_cursos);
    Bundle extras = getIntent().getExtras();
    //Obtenemos datos enviados en el intent.
    if (extras != null) {
       user  = extras.getString("user");
       id_usuario = extras.getInt("id_usuario");//usuario
    }else{
       user="error";
       }

    Tarea1 tarea1 = new Tarea1();
    tarea1.cargarContenido(getApplicationContext());
    tarea1.execute(listaJson); //Le pasamos la lista para modificarla

    listaJson.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i,
                long l) {
            String item = ((TextView)view).getText().toString();

            Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();

        }
    });
}
    //Creamos un listView a través de sus objetos Curso.
static class Tarea1 extends AsyncTask<ListView, Void, ArrayAdapter<mostrar_cursos>>
{
    Context contexto;
    ListView list;
    InputStream is;
    ArrayList<mostrar_cursos> listacursos = new ArrayList<mostrar_cursos>();

    public void cargarContenido (Context contexto)
    {
        this.contexto= contexto;
    }

    @Override
    protected ArrayAdapter<mostrar_cursos> doInBackground(ListView... params)
    {
        list = params[0];
        String resultado = "fallo";
        mostrar_cursos curs;



        //Creo la conexión HTTP

        HttpClient cliente = new DefaultHttpClient();
        HttpGet peticionGet = new HttpGet("http://192.168.0.100/android/sesion_profesor.php?id_usuario="+id_usuario+"");
        try{
            HttpResponse response = cliente.execute(peticionGet);
            HttpEntity contenido = response.getEntity();
            is = contenido.getContent(); //Contenido de la respuesta
        }catch (ClientProtocolException e)
        {
            e.printStackTrace();
        }catch (IOException e)
        {
            e.printStackTrace();
        }

        BufferedReader buferlector = new BufferedReader (new InputStreamReader(is));//leemos los datos del is
        StringBuilder sb = new StringBuilder();
        String linea = null;
        try{
            while((linea = buferlector.readLine())!=null)
            {
                sb.append(linea);
            }
        }catch (IOException e)
        {
            e.printStackTrace();
        }
        try{
            is.close(); //Cerramos el inputstream para no consumir recursos
        }catch (IOException e) {
            e.printStackTrace();
        }
        resultado = sb.toString(); //Pasamos lo que hemos recibido por parámetros a la variable resultado
        //En la variable resultado tengo: [{"curso":"1","clase":"A"}]
        try{
            JSONArray arrayJson = new JSONArray(resultado);
            for(int i= 0; i<arrayJson.length();i++){ //Recorro el string
                JSONObject objetoJson = arrayJson.getJSONObject(i); //Devuelvo el primer objeto (indice=0) {"curso":"1","clase":"A"}
                curs = new mostrar_cursos(objetoJson.getString("curso"), objetoJson.getString("clase"));
                listacursos.add(curs); //Añado el nuevo curso
            }
        }catch (JSONException e){
            e.printStackTrace();
        }
        ArrayAdapter<mostrar_cursos> adaptador = new ArrayAdapter<mostrar_cursos>(contexto, android.R.layout.simple_list_item_1, listacursos); //Contexto de ver clientes (Muestra la lista con los datos de clientes que le he pasado

        return adaptador; //Devuelve su dato al método onPostExecute
            }
    @Override
    protected void onPostExecute(ArrayAdapter<mostrar_cursos> result) 
    {
        list.setAdapter(result);
        }

    }
}

And an image of the listview:

enter image description here

Upvotes: 2

Views: 1127

Answers (1)

Raghunandan
Raghunandan

Reputation: 133560

Move this to onPostExecute

  listaJson.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i,
                long l) {
            String item = (String) adapterView.getItemAtPosition(i);
            Toast.makeText(getApplicationContext(), item, Toast.LENGTH_LONG).show();
            Intent intent = new Intent(ActivityName.this,SecondActivity.class);
            i.putExtra("key", item);
            startActivity(intent);

        }
    });

Upvotes: 2

Related Questions