RecyclerView跳转详情页遇空指针:TextView.setText调用空对象引用
解决RecyclerView跳转详情页的空指针异常问题
看你提供的报错日志和代码,这个空指针异常的原因非常明确:你在DetailPage.kt里调用的tv_item_name、tv_item_detail和img_item_photo这几个控件,在activity_detail.xml里根本不存在对应的ID,导致控件对象为null,调用setText()时直接触发了空指针。
问题具体分析
- 在
activity_detail.xml中,你的TextView和ImageView的实际ID是:- 头像:
extra_photo - 名称:
extra_name - 详情:
extra_detail
- 头像:
- 但在
DetailPage.kt的showDetailPersonalities()方法里,你却用了tv_item_name、tv_item_detail、img_item_photo这些和布局文件不匹配的ID,自然找不到控件实例,返回null。
修复方案
你有两种简单的修复方式,选其中一种即可:
方式1:修改DetailPage.kt中的控件引用,匹配布局文件的ID
因为你代码里用了kotlinx.android.synthetic扩展,直接把控件名改成布局里的ID就行:
private fun showDetailPersonalities(){ extra_name.text = intent.getStringExtra(EXTRA_NAME) extra_detail.text = intent.getStringExtra(EXTRA_DETAIL) Glide.with(this).load(intent.getIntExtra(EXTRA_PHOTO,0)).into(extra_photo) }
注:如果你的Android Studio版本较新,kotlin-android-extensions已经被官方废弃,更推荐使用ViewBinding方案,不过这个修改能快速解决当前问题。
方式2:修改activity_detail.xml中的ID,匹配代码里的控件名
把布局文件里的ID改成你代码里写的名字:
<de.hdodenhof.circleimageview.CircleImageView android:id="@+id/img_item_photo" <!-- 修改此处ID --> android:layout_width="match_parent" android:layout_height="422dp" android:contentDescription="@string/todo" tools:background="@drawable/ic_launcher_background" /> <TextView android:id="@+id/tv_item_name" <!-- 修改此处ID --> android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:layout_marginBottom="15dp" android:fontFamily="sans-serif" android:textAlignment="center" android:textAppearance="@style/TextAppearance.AppCompat.Display1" android:textSize="30sp" android:textStyle="bold" android:typeface="normal" /> <TextView android:id="@+id/tv_item_detail" <!-- 修改此处ID --> android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginBottom="10dp" android:fontFamily="sans-serif" android:textAlignment="viewStart" android:textSize="18sp" />
额外验证点
你在MainActivity里跳转时的参数传递是正常的,只要控件引用匹配正确,就能正常显示详情页数据了。
内容的提问来源于stack exchange,提问作者1988
相关产品推荐
相关产品推荐

