Create OnItemClickListener within a custom Listwiev with Json

1

I need to control the click on the custom Listview to perform an operation depending on which one is pressed.

I leave the code of the main page.

public class Mostrar_Productos extends Anadir_Productos_Principal {
    SmartImageView smartImageView;
    TextView txvnombre_listado;
    String nombrelistado;
    String imagenlistado;
    ArrayList<String> producto_array = new ArrayList<String>();
    ArrayList<String> pendiente_array = new ArrayList<String>();
    ListView list;
    ListadoProductosAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mostrar_productos);
        RecibirDatos();
        InsertarLogotipoyNombre();
        list = (ListView) findViewById(R.id.lv_productos);
        new TheTask().execute();
    }

    class TheTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... params) {
            String str = null;

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(
                        "http://XXXXXXXXXX/XXXXX/XXXXXXXXXXXXX.php");
                //Configuramos los parametos que vaos a enviar con la peticion HTTP POST
                List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                pairs.add(new BasicNameValuePair("supermercado", nombrelistado));
                httppost.setEntity(new UrlEncodedFormEntity(pairs));
                HttpResponse response = httpclient.execute(httppost);
                str = EntityUtils.toString(response.getEntity());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return str;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            String response = result.toString();
            try {
                JSONArray new_array = new JSONArray(response);

                for (int i = 0, count = new_array.length(); i < count; i++) {
                    try {
                        JSONObject jsonObject = new_array.getJSONObject(i);
                        producto_array.add(jsonObject.getString("nombre_producto").toString());
                        pendiente_array.add(jsonObject.getString("pendiente").toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                adapter = new ListadoProductosAdapter(Mostrar_Productos.this, producto_array, pendiente_array);
                list.setAdapter(adapter);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                // tv.setText("error2");
            }
        }
    }

    private void InsertarLogotipoyNombre() {
        smartImageView =(SmartImageView)findViewById(R.id.imagenlogo_listado);
        txvnombre_listado = (TextView)findViewById(R.id.tv_Nombre_listado);
        String urlfinal = "http://XXXXXXXXXXXXX/"+imagenlistado;
        Rect rect=new Rect(smartImageView.getLeft(), smartImageView.getTop(), smartImageView.getRight(), smartImageView.getBottom());
        smartImageView.setImageUrl(urlfinal, rect);
        txvnombre_listado.setText(nombrelistado.toString());
    }

    private void RecibirDatos() {
        Bundle extras = getIntent().getExtras();
        String nombre = extras.getString("nombre");
        String imagen = extras.getString("imagen");
        imagenlistado = imagen;
        nombrelistado = nombre;
    }
}

and here I leave the code of the Adapter.

public class ListadoProductosAdapter extends BaseAdapter {
    private Activity activity;
    private static ArrayList producto, pendiente;
    private static LayoutInflater inflater = null;

    public ListadoProductosAdapter(Activity a, ArrayList b, ArrayList bod) {
        activity = a;
        this.producto = b;
        this.pendiente = bod;

        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    public int getCount() {
        return producto.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        if (convertView == null)
            vi = inflater.inflate(R.layout.listado_productos, null);

        final CheckBox title2 =(CheckBox)vi.findViewById(R.id.ckb_apuntado);
        String product = producto.get(position).toString();
        String pendient = pendiente.get(position).toString();

        title2.setText(product);

        Boolean check = null;
        if (pendient.equals("SI")){
            check = true;
        } if (pendient.equals("NO")) {
            check = false;
        }

        title2.setChecked(check);
        return vi;
    }
}

I have been looking for a solution for several days, but I only find if the data is loaded through an array created manually and I bring the data from a remote server.

I hope your help and if you need some more information to say it. Thanks.

    
asked by user3737118 26.05.2016 в 21:53
source

2 answers

1

This would be a way:

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mostrar_productos);
        RecibirDatos();
        InsertarLogotipoyNombre();

       list = (ListView) findViewById(R.id.lv_productos);

       //configura listener.
       list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          //Object listItem = list.getItemAtPosition(position);
        Toast.makeText(getAplicationContext, "Click en la posición "  + position, Toast.LENGTH_SHORT).show();
       } 
     });

    new TheTask().execute();
  }

Regularly used:

  

setOnItemClickListener Used when one day click on an element   of the adapter

but you can also use:

  

OnItemLongClickListener Used when one day click on an element   of the adapter for a prolonged period.

     

setOnItemSelectedListener Used when an element of the adapter   is selected.

    
answered by 26.05.2016 / 23:09
source
0

You need to implement the listView method in your setOnItemClickListener(OnItemClickListener) . You can do directly:

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3) {
            String value = (String)adapter.getItemAtPosition(position); 
            Toast.makeText(TuActivity.this, value, Toast.LENGTH_SHORT).show();
    }
});

Additional to it; your code has details that would be good to correct.

  • Class names in Java are usually written using CamelCase , correct AnadirProductosPrincipal incorrect Anadir_Productos_Principal

  • The methods and variables are similar, but with the first letter lowercase, example recibirDatos

  • That way we maintain the global syntax and we communicate better.

        
    answered by 26.05.2016 в 22:06