-1

I have a problem with my CustomAdapter. The program was working fine with Android Studio until I hit at a roadblock that says:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference

My Code:

public class CustomAdapter extends BaseAdapter {
    private Activity activity;
    private LayoutInflater inflater;
    private ArrayList<ModuleModel> Items;

    TextView name, module, dueday, id;

    public CustomAdapter(Activity activity, ArrayList<ModuleModel> Items)
    {
        this.activity = activity;
        this.Items = Items;
    }
    @Override
    public int getCount() {
            return Items.size();
    }

    @Override
    public Object getItem(int i) {
        return Items.get(i);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        if(inflater == null)
        {
            inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        if(convertView != null) {
            convertView = inflater.inflate(R.layout.layout_item, null);
        }
        id = convertView.findViewById(R.id.tvID);
        name = convertView.findViewById(R.id.tvRowName);
        module = convertView.findViewById(R.id.tvRowModule);
        dueday = convertView.findViewById(R.id.tvInforDueDay);

        ModuleModel mm = Items.get(position);
        id.setText(mm.getID());
        name.setText(mm.getName());
        module.setText(mm.getModule());
        dueday.setText(mm.getDueday());

        return convertView;
    }
}
gehbiszumeis
  • 3,189
  • 4
  • 24
  • 37
  • 1
    Did you try to debug your code to see why your `convertView` is null ? Provide a bit more of the stacktrace to get the correct line where there is the NPE please – Maelig Jan 28 '19 at 09:48

3 Answers3

1

Can u change and try once?

In your code, the convertView is always null due to that it's throwing NLE to u

if(convertView != null) {
            convertView = inflater.inflate(R.layout.layout_item, null);
}

to

if(convertView == null) {
            convertView = inflater.inflate(R.layout.layout_item, null);
}
Raghavendra
  • 2,250
  • 21
  • 29
0

Try this

    id.setText(""+mm.getID());
Maulik Dadhaniya
  • 675
  • 9
  • 18
  • Just to inform the NLE is while doing the initialization i.e., View.findViewById(int) not while setting a value to the view. – Raghavendra Jan 28 '19 at 09:46
0

Your problem lies here

if(convertView != null) {
            convertView = inflater.inflate(R.layout.layout_item, null);
        }

You are not assigning convertView with new value when it is null so it throws error when it gets to the below code block.

Bach Vu
  • 2,158
  • 1
  • 14
  • 19