dimanche 3 juillet 2016

Null pointer reference from Adapter setOnClickListener

I have the following code and I'm getting a null pointer exception (see below). I want to retrieve the userName pointed to by the view holder. I've tried even to retrieve it via view (v) itself but I got the same exception. I don't understand why the value is null.

    public class ContactAdapter extends BaseAdapter {

        private Context mContext;


        public ContactAdapter(Context context) {

            mContext = context;
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder;

            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_contact, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);

            } else {

                holder = (ViewHolder) convertView.getTag();
            }

    holder.delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        ViewHolder vv = (ViewHolder)v.getTag();
                        TextView tv = (TextView) vv.userName.getText(); // Exception here - Line 120
                    }catch(Exception xx){

                    }
                }
     });
}

    private class ViewHolder {

            TextView userName;
            ImageView add, delete, block,profImage;

            public ViewHolder(View view) {

                userName = (TextView) view.findViewById(R.id.user_name);
                add = (ImageView) view.findViewById(R.id.add);
                delete = (ImageView) view.findViewById(R.id.delete);
                block = (ImageView) view.findViewById(R.id.block);
                profImage = (ImageView) view.findViewById(R.id.profile_image);
            }
        }

Here is the exception: enter image description here

Aucun commentaire:

Enregistrer un commentaire