2

Ive seen plenty of posts, plenty of tutorials but i can't find the key to make this work. I have a listView with friend requests,as u see these requests have 2 buttons (accept or deny) and i want to know how can i know which button is clicked (At the moment it doesnt even works to tell me if an item is clicked).

Please help, im like desperate.

Heres the code of the Activity

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class Solicitudes extends Activity {
    private ProgressDialog pDialog;
    private static final String SOLICITUDES_URL = "http://192.168.56.1/webservice/cargarSolicitudes.php";
    JSONParser jsonParser = new JSONParser();
    private ListView lv;
    // JSON IDS:

    private static final String TAG_POSTS = "posts";

    private static final String TAG_USERNAME = "username";
    private HashMap<String, String> user;
    SessionManager session;

    // array con los amigos
    private JSONArray mAmigos = null;
    // organiza los amigos en una lista.
    private ArrayList<HashMap<String, String>> mAmigosList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_solicitudes);
        lv = (ListView) findViewById(R.id.listViewSolicitudes);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // ListView Clicked
                int itemPosition = position;

                // ListView Clicked
                String itemValue = (String) lv.getItemAtPosition(position);

                // Show Alert
                Toast.makeText(
                        getApplicationContext(),
                        "Position :" + itemPosition + "  ListItem : "
                                + itemValue, Toast.LENGTH_LONG).show();


            }
        });


    }

    private void updateList() {
        // Para un ListActivity tenemos que tener un List Adapter. Este
        // simpleAdapter
        // utilizará nuestro ArrayList Hashmap actualizado. Utilizo
        // single_request.xml para
        // cada item en la lista y pongo la informaación correcta para cada ID.

        ListAdapter adapter = new SimpleAdapter(this, mAmigosList,
                R.layout.single_request, new String[] { TAG_USERNAME },
                new int[] { R.id.textViewAmigoUsuario });

        lv.setAdapter(adapter);

    }

    public void updateJSONdata() {
        // Session class instance
        session = new SessionManager(getApplicationContext());
        // get user data from session
        user = session.getUserDetails();
        String username = user.get(SessionManager.KEY_USERNAME);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", username));
        mAmigosList = new ArrayList<HashMap<String, String>>();

        JSONObject json = jsonParser.makeHttpRequest(SOLICITUDES_URL, "POST",
                params);

        // cuando parseamos JSON es conveniente hacer un catch de las
        // excepciones

        try {

            mAmigos = json.getJSONArray(TAG_POSTS);

            // Iterando para todos los post que nos devuelve el objeto json
            for (int i = 0; i < mAmigos.length(); i++) {
                JSONObject c = mAmigos.getJSONObject(i);

                // devuelve el contenido de la etiqueta
                String idUser1 = c.getString(TAG_USERNAME);

                // creando un nuevo HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                map.put(TAG_USERNAME, idUser1);
                // map.put(TAG_ID2, idUser2);

                // agrego el HashList al ArrayList
                mAmigosList.add(map);

            }

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

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        // cargando los amigos a través de AsynTask
        new buscarSolicitudes().execute();
    }

    public class buscarSolicitudes extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getApplicationContext());
            pDialog.setMessage("Cargando solicitudes...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
        }

        @Override
        protected Boolean doInBackground(Void... arg0) {
            updateJSONdata();
            return null;

        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            pDialog.dismiss();
            updateList();
        }
    }


}

The code of the activity_layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Buscar" >

    <TextView
        android:id="@+id/textViewSolicitudes"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_margin="10dp"
        android:gravity="center"
        android:text="@string/solicitudes"
        android:textColor="@color/AzulClaro" />


    <ListView 
        android:id="@+id/listViewSolicitudes"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@android:id/empty"
        android:layout_below="@id/textViewSolicitudes"
        tools:listitem="@layout/single_request"
        android:focusable="false"
        android:descendantFocusability="blocksDescendants"
        android:drawSelectorOnTop="true" />

</RelativeLayout>

And the code about the single_request layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#f0f0f0"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:orientation="vertical" >

        <LinearLayout
            android:id="@+id/boxSF1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:orientation="horizontal" >

            <ImageView
                android:id="@+id/imageUser"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/perfildefecto" />

            <RelativeLayout
                android:id="@+id/boxSF2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="2dp"
                android:orientation="vertical"
                android:padding="5dp" >

                <TextView
                    android:id="@+id/textViewAmigoUsuario"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom"
                    android:paddingBottom="2dip"
                    android:paddingLeft="5dp"
                    android:paddingTop="6dip"
                    android:textColor="#333"
                    android:textSize="16sp"
                    android:textStyle="bold" />


                    <Button
                        android:id="@+id/btnEliminar"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:layout_alignParentRight="true"
                        android:layout_below="@+id/textViewSolicitud"
                        android:layout_marginTop="30dp"
                        android:background="@drawable/denegar"
                        android:max="100" />

                    <Button
                        android:id="@+id/btnAgregar"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:layout_alignBaseline="@+id/btnEliminar"
                        android:layout_alignBottom="@+id/btnEliminar"
                        android:layout_marginRight="24dp"
                        android:layout_toLeftOf="@+id/btnEliminar"
                        android:background="@drawable/aceptar"
                        android:max="100" />

                    <TextView
                        android:id="@+id/textViewSolicitud"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:layout_centerVertical="true"
                        android:layout_below="@id/textViewAmigoUsuario"
                        android:layout_margin="10dp"
                        android:gravity="left"
                        android:text="@string/friend_request"
                        android:textColor="@color/AzulClaro" />

            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

3 Answers3

4

onItemClicked is not called because of the Button, in your row. Add

android:descendantFocusability="blocksDescendants"

to the root of your single_request layout

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
  • well, i guess im ready to suicide now because this works. But now if u click the Accept buttons or deny in any of the single_requests items, how do i know which one and the position? thanks! – Juan Belmonte Rodriguez Jul 30 '14 at 09:57
  • there is no need to suicide. It is called learning curve. About your second question, accept and deny are buttons. If you want those to respond to a click event you have to set for each of them an `OnClickListener`. So you will have three different behaviours. Two for the buttons and one for the row's click – Blackbelt Jul 30 '14 at 09:59
  • and where should i add that OnClickListener? Inside of the onItemClick?im so grateful! – Juan Belmonte Rodriguez Jul 30 '14 at 10:02
  • on the buttonInstance. For instance buttonInstance.setOnClickListener(...). The onClick method will be called from the system when a click event for that button is detected – Blackbelt Jul 30 '14 at 10:04
  • ive added this aceptar = (Button) findViewById(R.id.btnAgregar); aceptar.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { System.out.println("Clicked accept on item"+ itemPosition); } }); but it only works for the first 'single_request' layout, any ideas? : – Juan Belmonte Rodriguez Jul 30 '14 at 10:27
  • those buttons are part of the row of the ListView, if I understood correctly, so you have to look for them in the getView's method. You probably need a custom adapter, – Blackbelt Jul 30 '14 at 10:28
  • 1
    ooh damn.. no idea about how to build one, ill have to look tutorials for that. So much thanks for everything. – Juan Belmonte Rodriguez Jul 30 '14 at 10:43
1

In single_request layout you have focusable item like Button thats why onItemClick is not fired. set all focusable items focusability false.

code snippet for focusable item like button

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:clickable="false"
    android:text="Button" />

If you want to set onClick of those Buttons set it inside your CustomAdapter.

Kaushik
  • 6,150
  • 5
  • 39
  • 54
0

I have sane issue happen Instead of button try to use ImageView.

now your single_request_layout will like.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/boxSF1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="2dp"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/imageUser"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/perfildefecto" />

        <RelativeLayout
            android:id="@+id/boxSF2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:orientation="vertical"
            android:padding="5dp" >

            <TextView
                android:id="@+id/textViewAmigoUsuario"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom"
                android:paddingBottom="2dip"
                android:paddingLeft="5dp"
                android:paddingTop="6dip"
                android:textColor="#333"
                android:textSize="16sp"
                android:textStyle="bold" />


                <ImageView
                    android:id="@+id/btnEliminar"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_alignParentRight="true"
                    android:layout_below="@+id/textViewSolicitud"
                    android:layout_marginTop="30dp"
                    android:background="@drawable/denegar"
                    android:max="100" />

                <ImageView
                    android:id="@+id/btnAgregar"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_alignBaseline="@+id/btnEliminar"
                    android:layout_alignBottom="@+id/btnEliminar"
                    android:layout_marginRight="24dp"
                    android:layout_toLeftOf="@+id/btnEliminar"
                    android:background="@drawable/aceptar"
                    android:max="100" />

                <TextView
                    android:id="@+id/textViewSolicitud"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:layout_centerVertical="true"
                    android:layout_below="@id/textViewAmigoUsuario"
                    android:layout_margin="10dp"
                    android:gravity="left"
                    android:text="@string/friend_request"
                    android:textColor="@color/AzulClaro" />

        </RelativeLayout>
    </LinearLayout>
</LinearLayout>

I hope this will work.

bhavesh kaila
  • 761
  • 1
  • 5
  • 25