0

I have following code:

    public class MyListAdapter extends BaseAdapter {

    private final List<MyClass> mItems = new ArrayList<MyClass>();
...

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;
    final MyClass myItem = mItems.get(position);
    if (rowView == null) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rowView = inflater.inflate(R.layout.my_item, null);
        ViewHolder viewHolder = new ViewHolder();
        viewHolder.cbView = (CheckBox) rowView.findViewById(R.id.cbCheckBox);
        viewHolder.cbView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                myItem.setState(isChecked);
            }
        });
        rowView.setTag(viewHolder);
    }

I'm very uncomfortable with the listener. It refers to the myItem that created when convertView was null. What if I remove that item from the list (the position changes)? Or if I add some items in front of it? Will my code fail with "null exception"? Or perform incorrectly? How I should build it?

Michael
  • 1,014
  • 2
  • 15
  • 26

1 Answers1

0

if convertView is null then just create the view object... Now if a view is remove from mid of list, then view from bottom lift up and replace the space of deleted view. And As view is lift up the viewHolder object will created new and view hold updated viewHolder object.

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;
    final MyClass myItem = mItems.get(position);
    if (rowView == null) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rowView = inflater.inflate(R.layout.my_item, null);
       }
        ViewHolder viewHolder = new ViewHolder();
        viewHolder.cbView = (CheckBox) rowView.findViewById(R.id.cbCheckBox);
        viewHolder.cbView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                myItem.setState(isChecked);
            }
        });
        rowView.setTag(viewHolder);
    }
Arfan Mirza
  • 668
  • 1
  • 14
  • 24
  • What about `final MyClass myItem = mItems.get(position);`? It is created every time the `getView` is called. But only FIRST is used inside `onCheckedChanged`. – Michael Feb 14 '14 at 08:14
  • Yes, it will create every time when getView is called. – Arfan Mirza Feb 16 '14 at 15:16
  • But the listener is created once. It means that if the original item is deleted the listener will crush. – Michael Feb 17 '14 at 00:02