Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a parameter to onclick listener on a button in a listview row

Tags:

I just started android and I'm running into some problems.
I have created a ListView that is populated from a database.
Each row has a button to delete the item from the list and the database.

I am able to hook up an event listener to the button but I have not been able to determine the matching database record to be deleted.

My class is shown below

public class FeedArrayAdapter extends ArrayAdapter<Feed> implements OnClickListener
{
    private ARssEReaderDBAdapter dba;
    private String TAG = "FeedArrayAdapter";

    public FeedArrayAdapter(Context context, int textViewResourceId, List<Feed> items)          {
    super(context, textViewResourceId, items);
    Log.w(TAG, "List");


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Log.w(TAG, "getView");
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.feedlistrow, null);
    }
    Feed feed = getItem(position);
    if (feed != null) {
        TextView title = (TextView)v.findViewById(R.id.TextView01);
        if (title != null) {
            title.setText(feed.getTitle());
        }
        Button btnDelete = (Button)v.findViewById(R.id.btnDelete);
        btnDelete.setOnClickListener(this); //btnDeleteFeedListener
    }
    return v;
}

public void onClick(View v) {
    Log.w(TAG, "something got clicked: ");
}

So how can I pass the database record ID to the handler so I can use the database adapter to delete it?

like image 718
Richard Avatar asked Aug 12 '10 20:08

Richard


2 Answers

You should store the ID of the record in the Tag, call setTag() on your view, and to read in onclick call getTag()

like image 177
Pentium10 Avatar answered Oct 20 '22 10:10

Pentium10


Create a inner class that implements OnClickListener and then pass the position variable in the constructor.

 private Class MyClickListener implements OnClickListener {

    private int position;

    public MyClickListener(int position) {
       this.position = position;
    }

    public void onClick(View v) {
       System.out.println("position " + getPosition() + " clicked.");
    }

    public int getPosition() {
      return position;
    }

 }
like image 20
RoflcoptrException Avatar answered Oct 20 '22 11:10

RoflcoptrException