0

I have a custom listview and want to return / inflate depending on condition. i want rows displayed or not displayed depending on a condition.

In getView() i have the following

if (convertView == null) {

                // Inflate the layout
                LayoutInflater li = getLayoutInflater();
                convertView = li.inflate(
                        R.layout.contactos_list_item, null);

                contactViewHolder = new ContactViewHolder();

                contactViewHolder.imgContact = (ImageView) convertView
                        .findViewById(R.id.flag);
                contactViewHolder.txtViewContactName = (TextView) convertView
                        .findViewById(R.id.txtView_name);
                contactViewHolder.txtViewPhoneNumber = (TextView) convertView
                        .findViewById(R.id.txtview_number);

                convertView.setTag(contactViewHolder);
            } else {
                contactViewHolder = (ContactViewHolder) convertView.getTag();
            }

and i want to return

if(condition)
{
  return convertView;
}
else
{
   LayoutInflater li = getLayoutInflater();
   convertView=li.inflate(R.layout.row_null,null);
   return convertView;
}

i have the appropriate xml layout but the application stops working. what should i change so the

Cœur
  • 37,241
  • 25
  • 195
  • 267
Ingolf Krauss
  • 161
  • 1
  • 2
  • 23

1 Answers1

0

While you don't inflate a new layout in if condition, i bet you get a NullPointerException, because you can have the wrong layout from the recycling mechanism.

Change your code like that:

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

    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    if (condition) {
       convertview = inflater.inflate(R.layout.first_layout, null);
       //do your stuff

     } else {
       convertview = inflater.inflate(R.layout.second_layout, null);
       // do your stuff
     }
    return convertview;
}
Rami
  • 7,879
  • 12
  • 36
  • 66