Search code examples
javaandroidlistadapter

Accessing objects inside a custom ListAdpater events clicks


I have this implementation of ListAdapter:

public class TaskAdapter implements ListAdapter, View.OnClickListener {

Context                 context;

List<Task>              tasks;

// View adapterView;
public TaskAdapter(Context context, List<Task> tasks) {
    super();
    this.context = context;
    this.tasks = tasks;
} ...

@Override
public View getView(int position, View convertView, ViewGroup parent) 
{
    Task data = tasks.get(position);
    Button task_menu_bt = (Button)root.findViewById(R.id.taskMenuButton);

        task_menu_bt.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {
                **//     How to access current Task data??  i can not do tasks.get(position)**
            }
        });

}

My question is how can i access Task data from inside the onClick event on a button located in the item row (not the view click but a button on the list view)?

My task class contains for exmaple getName() methods and others...


Solution

  • Since you are using onClickListener's implement as an inner class, the variable won't be accessable inside it. So you should either declare a Task variable at Adapter level, basically a member of TaskAdapter or make it final either if it will work

        public class TaskAdapter implements ListAdapter, View.OnClickListener {
    
    Context                 context;
    
    List<Task>              tasks;
    Task data;
    
    // View adapterView;
    public TaskAdapter(Context context, List<Task> tasks) {
        super();
        this.context = context;
        this.tasks = tasks;
    } ...
    
    
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) 
    {
        data = tasks.get(position);
        Button task_menu_bt = (Button)root.findViewById(R.id.taskMenuButton);
    
            task_menu_bt.setOnClickListener(new View.OnClickListener() 
            {
                @Override
                public void onClick(View v) 
                {
                    **//     How to access current Task data??  i can not do tasks.get(position)**
                }
            });
    
    final Task data = tasks.get(position);
    

    One of the better way to access an item is to override the getItem method and return the object from the data source there.

    public Object getItem (int position){
        return (Task)tasks.get(position);
    }