1

I have created a ListView that is populated from a database.Each row has a button to update the item value from the list and the database.I want to add onClick event for buttons used in item of ListView. How can I assign an OnClickListener for buttons for list items ?

enter image description here

addtooutlet.xml

   <?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="#ffffff">

<ListView
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

</LinearLayout>

addtooutlet_list_item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:padding="5dip" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="46dp"
    android:background="#ffffff"
    android:padding="5dip"
    android:weightSum="100" >

    <TextView
        android:id="@+id/item_bname"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="25"
        android:padding="2dp"
        android:text="Hello"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#000000"
        android:textSize="12dip" />

    <TextView
        android:id="@+id/item_bid"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="25"
        android:padding="2dp"
        android:text="Hello"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#000000"
        android:textSize="12dip" />

    <Button
        android:id="@+id/item_button"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/item_bname"
        android:layout_marginRight="16dp"
        android:layout_weight="50"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:padding="2dp"
        android:text="Join"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#000000"
          android:textSize="12dip" />
   </LinearLayout>

</LinearLayout>

AddTooutlet.java

 public class AddToOutlet extends ListActivity {
SessionManager session;
String success, cus_id, bus_id;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.addtooutlet);
    session = new SessionManager(getApplicationContext());
    session.checkLoginback();
    // get user data from session
    HashMap<String, String> user = session.getUserDetails();
    // ID
    final String cus_id = user.get(SessionManager.KEY_ID);
    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair("cus_id", cus_id));
    String response = null;
    try {
 response=LoginHttpClient.executeHttpPost("http://10.0.2.2/android_api/add_to_outlet.php",postParameters);
        JSONObject json = new JSONObject(response);
        JSONArray jArray = json.getJSONArray("customer");
        for (int i = 0; i < jArray.length(); i++) {
            HashMap<String, String> map = new HashMap<String, String>();
            JSONObject json_data = jArray.getJSONObject(i);
            map.put("bus_name", json_data.getString("bus_name"));
            map.put("bus_id", json_data.getString("bus_id"));
            success = json_data.getString("success");
            mylist.add(map);
        }
    } catch (Exception e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }
    ListAdapter adapter = new SimpleAdapter(this, mylist,
            R.layout.addtooutlet_list_item, new String[] { "bus_name",
                    "bus_id" },
            new int[] { R.id.item_bname, R.id.item_bid });
    setListAdapter(adapter);
}

public class Myadapter extends ArrayAdapter<String> {

    private OnClickListener callback;

    public Myadapter(Context context, int resource, int textViewResourceId,
            String[] strings, OnClickListener callback) {
        super(context, resource, textViewResourceId, strings);
        this.callback = callback;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = getLayoutInflater();
        View row = inflater.inflate(R.layout.addtooutlet_list_item, parent,
                false);

        Button buttonEdit = (Button) row.findViewById(R.id.item_button);

        buttonEdit.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.i("xx", "Button pressed!");
            }
        });

        return convertView;
    }

    private LayoutInflater getLayoutInflater() {
        // TODO Auto-generated method stub
        return null;
    }

}
}
1
  • Post your MyAdapter class Commented Feb 26, 2014 at 10:15

1 Answer 1

6

You have

 View row = inflater.inflate(R.layout.addtooutlet_list_item, parent,
            false);

But you return

return convertView;

Should be

View convertView = inflater.inflate(R.layout.addtooutlet_list_item, parent,
            false);

And

 Button buttonEdit = (Button) convertView.findViewById(R.id.item_button);

And

return convertView;

Edit:

As suggested in the comment by blackbelt. You are not using Custom ArrayAdapter

You probably meant

Myadapter adapter = new MyAdapter(ActivityName.this,R.layout.addtooutlet_list_item,mylist);
setListAdapter(adapter);

Then

 ArrayList<HashMap<String,String> map;
 LayoutInflater mInflater;
 public Myadapter(Context context, int resource, int textViewResourceId,
        ArrayLsit<HashMap<String,String> map, OnClickListener callback) {
    super(context, resource, textViewResourceId, map);
    this.map = map;
    mInflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder holder;
    if(convertView ==null)
    {
    holder = new ViewHolder();
    convertView = mInflater.inflate(R.layout.addtooutlet_list_item, parent,
            false);
    holder.tv1 = (TextView) convertView.findViewById(R.id.textView1);
    holder.tv2 = (TextView) convertView.findViewById(R.id.textView2);
    holder.b = (Button) convertView.findViewById(R.id.item_button);
    convertView.setTaf(holder); 
    }else{
           holder =(ViewHolder) convertView.getTag();
    }
    HashMap<String,String> hm = map.get(position);
    holder.tv1.setText(hm.get(postion).get("bus_name").toString());
    holder.tv2.setText(hm.get(postion).get("bus_id").toString());
    holder.b.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
            Log.i("xx", "Button pressed!");
        }
    });

    return convertView;
}

The ViewHodler

static class ViewHolder
{
     Button b;
     TextView tv1,tv2; 
} 

Now you should have a textview's in layout.addtooutlet_list_item.xml and update views in getView.

Also consider using a ViewHolder Pattern

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

Sign up to request clarification or add additional context in comments.

12 Comments

but he is not using MyAdapter. He is using a SimpleAdapter. And still if what you point it out was the issue, his app was crashing
Another minor thing, you could suggest him to avoid to inflate every time the convertView
@Amardeep Look at the edited code. Only thing missing is a ViewHolder
@Raghunandan, +1 for great co-operation. as well as answer.,
@Amardeep edited further to add view holder. have 2 textviews and a button in addtooutlet_list_item.xml. rest all copy paste
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.