Kotlin Android开发中Intent传值后extras.getString返回null问题求解
问题根因及修复方案
核心错误:Intent传参时错误调用了字符串的get方法
PrayerAdapter的点击事件中你写了如下代码:
intent.putExtra("ARABIC_TEXT", strContentArabic?.get(position)) intent.putExtra("LATIN_TEXT", strContentLatin!![position]) intent.putExtra("TRANSLATION_TEXT", strContentTranslation!![position]) intent.putExtra("DESCRIPTION_TEXT", strContentDescription!![position])
此处的strContentArabic已经是当前条目对应的完整字符串,get(position)(即[]运算符)是取出字符串中索引为position的单个Char类型字符,并不是你要传递的完整字符串,如果position大于字符串长度还会直接触发崩溃,你拿到的空值就是这个原因导致的。
修复方式:
直接传递完整字符串即可,去掉取字符下标的逻辑:
intent.putExtra("ARABIC_TEXT", strContentArabic) intent.putExtra("LATIN_TEXT", strContentLatin) intent.putExtra("TRANSLATION_TEXT", strContentTranslation) intent.putExtra("DESCRIPTION_TEXT", strContentDescription)
其他需要修复的潜在问题
- Adapter上下文被覆盖导致inflater异常
PrayerAdapter构造函数已经传入了context,但是类内部又重新定义了private val context: Context? = null,覆盖了传入的上下文,会导致LayoutInflater初始化时传入null,引发布局加载异常。
修复:删除类内部冗余的context定义,直接使用构造传入的context即可:
class PrayerAdapter(private val context: Context, private val prayerContentList: MutableList<PrayerModel>) : RecyclerView.Adapter<PrayerViewHolder>() { // 删除冗余的 private val context: Context? = null 定义 private val inflater = LayoutInflater.from(context) // 其余代码不变 }
- 游标关闭逻辑错误
DatabaseLists的查询逻辑里,游标关闭的判断写反了,应该是游标使用完无论是否有数据都要关闭,而不是只有游标已经关闭的时候才调用close方法。
修复:将游标关闭逻辑移到循环外层,用try-finally保证资源释放:
val contentList = ArrayList<PrayerModel>() try { if (cursor.moveToFirst()) { while (!cursor.isAfterLast) { val contents = PrayerModel( cursor.getString(cursor.getColumnIndex("prayer_name")), cursor.getString(cursor.getColumnIndex("ayah_name")), cursor.getString(cursor.getColumnIndex("arabic")), cursor.getString(cursor.getColumnIndex("latin")), cursor.getString(cursor.getColumnIndex("translate")), cursor.getString(cursor.getColumnIndex("description")) ) contentList.add(contents) cursor.moveToNext() } } } finally { if (!cursor.isClosed) { cursor.close() } }
- 接收参数时空指针风险
PrayerReadActivity里接收参数直接调用toString(),如果值为null会得到字符串"null"而非空值,建议增加空值兜底逻辑:
val arabic = intent.getStringExtra("ARABIC_TEXT") ?: "" val latin = intent.getStringExtra("LATIN_TEXT") ?: "" val translation = intent.getStringExtra("TRANSLATION_TEXT") ?: "" val description = intent.getStringExtra("DESCRIPTION_TEXT") ?: ""
内容的提问来源于stack exchange,提问作者nadhif Aini
相关产品推荐
相关产品推荐

