-3

I have a problem with an app that i try to run. I have a listview which is made from names that i add in an edittext of a class. When there are no items, when i move to listview the app crashes and i get that error:

java.lang.NullPointerException: Attempt to invoke interface method int java.util.List.size() on a null object reference

While I have one or more items in listview I can see them without crashes or errors. Can you help me please? Below is my code.

public class ListAdapter extends BaseAdapter {
Context context;
List<Student> valueList;

public ListAdapter(List<Student> listValue, Context context)
{
    this.context = context;
    this.valueList = listValue;
}

@Override
public int getCount()
{
    return this.valueList.size();
}

@Override
public Object getItem(int position)
{
    return this.valueList.get(position);
}

@Override
public long getItemId(int position)
{
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    ViewItem viewItem;
    convertView = null;

    if(convertView == null)
    {

        viewItem = new ViewItem();

        LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

        convertView = layoutInfiater.inflate(R.layout.listviewitem, null);

        viewItem.TextViewStudentName = (TextView)convertView.findViewById(R.id.textView1);

        convertView.setTag(viewItem);

    }
    else
    {
        viewItem = (ViewItem) convertView.getTag();
    }

    viewItem.TextViewStudentName.setText(valueList.get(position).StudentName);


    return convertView;}}
class ViewItem{TextView TextViewStudentName;}

The error is located in command return this.valueList.size();. If you need i can post the other classes of my code too. Thank you in advance!

hsm59
  • 1,991
  • 19
  • 25
Alex
  • 41
  • 7

1 Answers1

0

Hi Please check before setting adapter code is following.

if(yourDataList!=null && yourDataList.size() > 0 )
{
  yourListOrRecyclerView.setAdapter(adapter);
}

please do it like above which solved your problem.

Jyubin Patel
  • 1,373
  • 7
  • 17
  • 1
    he probably forgot to initialize the list List list=new ArrayList<>(); spliting the two conditions is better I think if(list==null){ //do sth ... try to figure out what causes the list to be null. } if(list.size() > 0){ // you can show the user that this is an empty list. it's a good practice. } – Bishoy Kamel Jan 11 '18 at 11:04