Android ListView下滑会报空指针异常

运行截图
Android ListView下滑会报空指针异常_第1张图片
错误信息:
Android ListView下滑会报空指针异常_第2张图片
错误代码:

 public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
       // Log.d("size",bookList.size()+"");
        Book book=getItem(position);
        View view;
        ViewHolder viewHolder;
        if(convertView==null){
            view= LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
            viewHolder=new ViewHolder();
            viewHolder.bookAuthor=view.findViewById(R.id.book_item_author);
            viewHolder.bookTitle=view.findViewById(R.id.book_item_title);
            viewHolder.bookLastChapter=view.findViewById(R.id.book_item_lastChapter);

        } else{
           view=convertView;
           viewHolder=(ViewHolder) view.getTag();
        }
        viewHolder.bookAuthor.setText(book.getAuthor());
        viewHolder.bookTitle.setText(book.getTitle());
        viewHolder.bookLastChapter.setText(book.getLastChapter());
        return view;
    }

错误原因:
ListView滑动后,viewHolder内的变量不能找到了。
解决方法:
convertView为null时候,设置 view.setTag(viewHolder);

 public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
       // Log.d("size",bookList.size()+"");
        Book book=getItem(position);
        View view;
        ViewHolder viewHolder;
        if(convertView==null){
            view= LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
            viewHolder=new ViewHolder();
            viewHolder.bookAuthor=view.findViewById(R.id.book_item_author);
            viewHolder.bookTitle=view.findViewById(R.id.book_item_title);
            viewHolder.bookLastChapter=view.findViewById(R.id.book_item_lastChapter);
            view.setTag(viewHolder);
        } else{
           view=convertView;
           viewHolder=(ViewHolder) view.getTag();
        }
        viewHolder.bookAuthor.setText(book.getAuthor());
        viewHolder.bookTitle.setText(book.getTitle());
        viewHolder.bookLastChapter.setText(book.getLastChapter());
        return view;
    }

你可能感兴趣的:(java,android)