我将Parcelable
对象中的Intent
对象放入下一个Activity
中:
val intent = Intent(mContext, ShowTestActivity::class.java)
intent.putExtra("test", test)
Log.d("myLog", "${intent.getParcelableExtra<Test>("test")}") // No problem
mContext.startActivity(intent)
并在下一个
Activity
中获得该对象:if (!intent.hasExtra("test")) throw Exception("Intent doesn't has 'test' extra")
val test: Test = intent.getParcelableExtra("test")
这里抛出异常:
public open class QBase(): Parcelable {
...
protected constructor(parcel: Parcel?) : this() {
parcel?.let {
question = parcel.readString() // parcel.readString() must not be null
helpText = parcel.readString()
qValue = parcel.readDouble()
qType = QType.valueOf(parcel.readString())
}
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(question)
parcel.writeString(helpText)
parcel.writeDouble(qValue)
parcel.writeString(qType.name)
}
...
}
并在测试中:
public class Test(): Parcelable {
...
public var questions: ArrayList<QBase> = ArrayList()
constructor(parcel: Parcel?): this() {
parcel?.let {
...
parcel.readTypedList(questions, QBase.CREATOR)
}
}
override fun writeToParcel(p: Parcel?, p1: Int) {
p?.let {
...
it.writeTypedList(questions)
}
}
...
}
这是一个异常(exception):
最佳答案
question = parcel.readString() // parcel.readString() must not be null
也许您定义的question
字段是一个非空字段,如果parcel.readString()
的结果返回空值,则会抛出java.lang.IllegalStateException
,只需将val question: String
的定义更改为val question: String?
,然后重试。
关于android - IllegalStateException:parcel.readString()不能为null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45688232/