今天在做一个即时通讯回话列表时,遇到int android.support.v7.widget.RecyclerView$ViewHolder.mItemViewType' on a null..空指针问题,费劲心思才找到报空指针的原因:
代码是这样的,有多种布局类型
@Override public int getItemViewType(int position) { BmobIMMessage message = msgs.get(position); if(message.getMsgType().equals(BmobIMMessageType.IMAGE.getType())){ return message.getFromId().equals(currentUid) ? TYPE_SEND_IMAGE: TYPE_RECEIVER_IMAGE; }else if(message.getMsgType().equals(BmobIMMessageType.LOCATION.getType())){ return message.getFromId().equals(currentUid) ? TYPE_SEND_LOCATION: TYPE_RECEIVER_LOCATION; }else if(message.getMsgType().equals(BmobIMMessageType.VOICE.getType())){ return message.getFromId().equals(currentUid) ? TYPE_SEND_VOICE: TYPE_RECEIVER_VOICE; }else if(message.getMsgType().equals(BmobIMMessageType.TEXT.getType())){ return message.getFromId().equals(currentUid) ? TYPE_SEND_TXT: TYPE_RECEIVER_TXT; }else if(message.getMsgType().equals(BmobIMMessageType.VIDEO.getType())){ return message.getFromId().equals(currentUid) ? TYPE_SEND_VIDEO: TYPE_RECEIVER_VIDEO; }else if(message.getMsgType().equals("agree")) {//显示欢迎 return TYPE_AGREE; }else{ // return -1; return TYPE_AGREE; }
然后这是
getItemCount()
@Override public int getItemCount() { return msgs.size(); }
最后发现是因为itemCount与viewType不匹配导致的
例如:
recyclerview总共有6种类型,现在只写了一种类型测试,其他的都没有些,才导致报空,然后在getItemCount中return 1; 就ok了
在实现即时通讯回话列表时遇到RecyclerView空指针异常,具体为'int android.support.v7.widget.RecyclerView$ViewHolder.mItemViewType' on a null object reference。问题根源在于itemCount与viewType不匹配,当recyclerview有多种布局类型,但只定义了一种类型进行测试时,会导致该错误。修复方法是在getItemCount方法中返回正确的布局数量,例如返回1。

5866

被折叠的 条评论
为什么被折叠?



