我尝试通过使用intent.putExtra(“ result”,resultBean)将Extra传递给另一个Activity,但是出现以下错误
android.os.BadParcelableException: Parcelable protocol requires a Parcelable.Creator object called CREATOR on class com.tai.androidtai.domain.bean.ResultBean
我试图通过stackoverflow找到解决方案,但没有找到。
我试图遵循readparcel和writeparcel之间的相同顺序,但是并没有改变任何东西。
这是我的以下代码:
活动:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_user_details)
ButterKnife.bind(this)
AndroidInjection.inject(this)
mPresenter.subscribe(this)
displayAllUserInformation(intent.getParcelableExtra("result"))
}
Bean:
class ResultBean private constructor(parcel: Parcel) : Parcelable {
@SerializedName("id")
private var mId: Int? = null
@SerializedName("name")
private var mName: String? = ""
@SerializedName("status")
private var mStatus: String? = ""
@SerializedName("species")
private var mSpecies: String? = ""
@SerializedName("gender")
private var mGender: String? = ""
@SerializedName("image")
private var mImageUrl: String? = ""
init {
mId = parcel.readInt()
mName = parcel.readString()
mStatus = parcel.readString()
mSpecies = parcel.readString()
mGender = parcel.readString()
mImageUrl = parcel.readString()
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(mId!!)
dest.writeString(mName)
dest.writeString(mStatus)
dest.writeString(mSpecies)
dest.writeString(mGender)
dest.writeString(mImageUrl)
}
override fun describeContents(): Int {
return 0
}
fun getId(): Int {
return mId!!
}
fun getName(): String {
if (mName == null) {
mName = ""
}
return mName!!
}
fun getStatus(): String {
if (mStatus == null) {
mStatus = ""
}
return mStatus!!
}
fun getSpecies(): String {
if (mSpecies == null) {
mSpecies = ""
}
return mSpecies!!
}
fun getGender(): String {
if (mGender == null) {
mGender = ""
}
return mGender!!
}
fun getImageUrl(): String {
if (mImageUrl == null) {
mImageUrl = ""
}
return mImageUrl!!
}
companion object {
@SuppressLint("ParcelCreator")
val CREATOR: Parcelable.Creator<ResultBean> = object : Parcelable.Creator<ResultBean> {
override fun createFromParcel(parcel: Parcel): ResultBean {
return ResultBean(parcel)
}
override fun newArray(size: Int): Array<ResultBean?> {
return arrayOfNulls(size)
}
}
}
}
谢谢您的帮助
答案 0 :(得分:0)
我不知道为什么,但是我只需要在val CREATOR上方添加“ @JvmField”
答案 1 :(得分:0)
问题在于书写或读取包裹。要解决此问题,请删除所有可包裹的实现或重写的方法,然后再次使用适当的实现重写该方法。您只需要按alt + Enter即可覆盖方法。
答案 2 :(得分:0)
您编写的语法有问题,并且JVM无法将其识别为CREATOR
的{{1}}。代替这个:
Parcelable
使用以下语法:
companion object {
@SuppressLint("ParcelCreator")
val CREATOR: Parcelable.Creator<ResultBean> = object : Parcelable.Creator<ResultBean> {
override fun createFromParcel(parcel: Parcel): ResultBean {
return ResultBean(parcel)
}
override fun newArray(size: Int): Array<ResultBean?> {
return arrayOfNulls(size)
}
}
}