NullPointerException in custom adapter getView

后端 未结 3 689
青春惊慌失措
青春惊慌失措 2020-12-18 04:12

I\'m coding a custom adapter for a ListView that has a custom list to it.

obviously, I have to write the getView function. so here is my code:



        
相关标签:
3条回答
  • 2020-12-18 04:25

    Change this:

    vi = inflater.inflate(R.layout.result_list_item, null);
    

    To this:

    vi = inflater.inflate(R.layout.result_list_item, parent, false);
    

    this is how your adapter should be:

    public class NoPicAdapter extends ArrayAdapter<NewAndCalendar> {
    
        private ArrayList<NewAndCalendar> data;
        private Activity mActivity;
        private LayoutInflater inflater = null;
    
        public NoPicAdapter(Activity a, ArrayList<NewAndCalendar> d) {
            super(a, R.layout.no_pic_list_item, d);
            mActivity = a;
            data = d;
            inflater = (LayoutInflater) mActivity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
    
    
        @Override
        public View getView(int position, @Nullable View convertView, ViewGroup parent) {
            View vi = convertView;
            if (vi == null)
                vi = inflater.inflate(R.layout.no_pic_list_item, parent, false);
            TextView title = (TextView) vi.findViewById(R.id.noPicTitle);
            TextView subtitle = (TextView) vi.findViewById(R.id.noPicSubtitle);
    
            title.setText(data.get(position).getmTitle());
            subtitle.setText(data.get(position).getmPubDate());
    
            return vi;
        }
    
    }
    
    0 讨论(0)
  • 2020-12-18 04:33

    Try this

    vi = LayoutInflater.from(mActivity).inflate(R.layout.result_list_item, null);

    if mActivity is your Activity context passed from the activity where you are creating the object of this adapter.

    0 讨论(0)
  • 2020-12-18 04:45

    are you initializing inflater? if not initialize it.

    inflater = getLayoutInflater();
    

    or

     inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
    0 讨论(0)
提交回复
热议问题