Android listview item click

1.8k views Asked by At

I'm trying to get into a listview items have different action when pressed, this action depends on a variable "state", but the problem is that all the items are in the same action, here the code:

for(int i = 0; i < json.length(); i++){
                    JSONObject c = json.getJSONObject(i);
                    // Storing  JSON item in a Variable
                    String  codigo = c.getString(TAG_CODIGO);
                    String  asignatura = c.getString(TAG_NOMBRE);
                    int  estado  = c.getInt("estado");
                    final int maxhoras = c.getInt("maxhoras");
                    final String idprogramacion = c.getString("programacionid");

                    // Adding value HashMap key => value
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(TAG_CODIGO, codigo);
                    map.put(TAG_NOMBRE, asignatura);

                    jsonlist.add(map);
                    list=(ListView)findViewById(R.id.lvclases);
                    ListAdapter adapter = new SimpleAdapter(Bienvenida.this, jsonlist,
                            R.layout.listview,
                            new String[] { TAG_CODIGO,TAG_NOMBRE, }, new int[] {
                            R.id.codigo, R.id.nombre,
                    });
                    list.setAdapter(adapter);
                    if(estado == 1) {
                        Log.e("estado", ""+estado);
                        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view,
                                                    int position, long id) {
                                Intent i = new Intent(Bienvenida.this, registroAsistencia.class);
                                i.putExtra("programacion",  idprogramacion);
                                i.putExtra("maxhoras",  maxhoras);
                                startActivity(i);
                                /*Toast toast1 = Toast.makeText(getApplicationContext(), "Correcto: el usuario existe", Toast.LENGTH_SHORT);
                                toast1.show();*/
                                //Toast.makeText(Bienvenida.this, "You Clicked at " + jsonlist.get(+position).get("asignatura"), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }else{
                        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                            @Override
                            public void onItemClick(AdapterView<?> parent, View view,
                                                    int position, long id) {
                                Toast.makeText(Bienvenida.this, "la clase aún no ha comenzado " + jsonlist.get(+position).get("asignatura"), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }

I am working on android studio, I appreciate the help

3

There are 3 answers

1
Chintan Soni On BEST ANSWER

Acually, this is not an answer to your question. But after watching your code it seems that you are not implementing ListView in a correct way.

A simple way to work with ListView goes through following abstract steps:

Make your Collection Ready -> Prepare the Adapter from the collection -> Set this adapter to ListView

In your case, assuming you are calling web services for getting data and your web services is responding with JSON array.

Now, make a POJO(plain old Java object) class like:

public class MyListItem{
    private String codigo;
    private String asignatura;
    private int estado;
    private int maxhoras;
    private String idprogramacion;

    public MyListItem(String codigo, String asignatura, int estado, int maxhoras, String idprogramacion){
        this.codigo = codigo;
        this.asignatura = asignatura;
        this.estado = estado;
        this.maxhoras = maxhoras;
        this.idprogramacion = idprogramacion;
    }

    // you can write getter setter methods for this
    public int get_estado(){
        return estado;
    }

    public String get_idprogramacion(){
        return idprogramacion;
    }

    public int get_maxhoras(){
        return maxhoras;
    }

    public String get_asignatura(){
        return asignatura;
    }
}

Now, prepare list like:

ArrayList<MyListItem> mArrayList = new ArrayList<>();

for(int i = 0; i < json.length(); i++){
    JSONObject c = json.getJSONObject(i);
    mArrayList.Add(
        new MyListItem(
            c.getString(TAG_CODIGO),
            c.getString(TAG_NOMBRE),
            c.getInt("estado"),
            c.getInt("maxhoras"),
            c.getString("programacionid")
        )
    );
}

Now, you are ready with list, just pass it to your custom adapter. If you are not aware of preparing Custom Adapter, check this link.

Once you are ready with making custom adapter, pass the list to this adapter like:

MyCustomAdapter adapter = new MyCustomAdapter(context, mArrayList);

Note: Above line strictly depends constructor of your custom adapter, say, MyCustomAdapter

After that, you are ready with your adapter, set it to your ListView, like:

list.setAdapter(adapter);

Now, here you set the OnItemClickListener

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
     @Override
     public void onItemClick(AdapterView<?> parent, View view,
                                                    int position, long id) {
         MyListItem item = (MyListItem)parent.getItem(position);
         if(item.get_estado() == 1)
         {
             Intent i = new Intent(Bienvenida.this, registroAsistencia.class);
             i.putExtra("programacion",  item.get_idprogramacion());
             i.putExtra("maxhoras",  item.get_maxhoras());
             startActivity(i);
         }
         else{
             Toast.makeText(Bienvenida.this, "la clase aún no ha comenzado " + item.get_asignatura(), Toast.LENGTH_SHORT).show();
         }

      }
});

Hope you get what you are trying to achieve..

This should help you out.

0
ThaiPD On

Problem is estado variable, it's global varible, so When you use listview.setOnItemClickListener(...) that mean all the item in listview will be the same action with your above code.

Solution is you should create your own custom adapter and then implement OnItemClickListener in your adapter, base on different states to set different actions for item . Also you can setOnClickListener in getView() in Adapter and base on state also.

Please refer as below :

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  @Override
  public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
     int estado = -1;
     // you should do something like this
    /* ********** */
     YourItem item = ((YourItemsData)data).get(position);
     estado = item.getState();
     /* ********** */
     if(estado == 1) {
          Intent i = new Intent(Bienvenida.this, registroAsistencia.class);
          i.putExtra("programacion",  idprogramacion);
          i.putExtra("maxhoras",  maxhoras);
          startActivity(i);

     } else {
               // Do something else
     }
   }

});

4
Bidhan On

Instead of having two different onClickListeners(), try using only one and move your if-else block inside of the onItemClick() method

 list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view,
                                                int position, long id) {
         if(estado == 1) {
              Intent i = new Intent(Bienvenida.this, registroAsistencia.class);
              i.putExtra("programacion",  idprogramacion);
              i.putExtra("maxhoras",  maxhoras);
              startActivity(i);

         } else {
                   // Do something else
         }
       }
   });