一個(gè)簡(jiǎn)單的數(shù)據(jù)類繼承Parcelable的代碼如下:
data class VideoBean(
val duration: String,
val score: Double,
val description: String,
val loadURL: String,
val shareURL: String,
val pic: String,
val title: String,
var roomId: String
) : Parcelable {
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
with(this) {
dest.writeString(duration)
dest.writeDouble(score)
dest.writeString(description)
dest.writeString(loadURL)
dest.writeString(shareURL)
dest.writeString(pic)
dest.writeString(title)
dest.writeString(roomId)
}
}
constructor(source: Parcel) : this(
source.readString(),
source.readDouble(),
source.readString(),
source.readString(),
source.readString(),
source.readString(),
source.readString(),
source.readString()
)
companion object {
@JvmField val CREATOR: Parcelable.Creator<VideoBean> = object : Parcelable.Creator<VideoBean> {
override fun createFromParcel(source: Parcel): VideoBean {
return VideoBean(source)
}
override fun newArray(size: Int): Array<VideoBean?> {
return arrayOfNulls(size)
}
}
}
}
一級(jí)的類序列化很簡(jiǎn)單岂座。
一般如果啟動(dòng)一個(gè)Activity的時(shí)候大刊,要傳入一些數(shù)據(jù)汽纤,我會(huì)寫(xiě)一個(gè)如下的接口:
public static void launch(Context context, VideoBean videoBean) {
Intent intent = new Intent()
.setClass(context, VideoInfoActivity.class)
.putExtra(EXTRA_VIDEO_BEAN, videoBean);
context.startActivity(intent);
}
然后在Activity的onCreate()里獲取該數(shù)據(jù)videoBean = getIntent().getParcelableExtra(EXTRA_VIDEO_BEAN);
但是有的時(shí)候會(huì)發(fā)現(xiàn)獲取到的videoBean會(huì)為null魄揉,而有的時(shí)候卻不會(huì)鞍盗,一開(kāi)始遇到這類問(wèn)題的時(shí)候會(huì)很不解妇押,但仔細(xì)看log跷究,會(huì)發(fā)現(xiàn)有這么一段錯(cuò)誤日志java.lang.IllegalStateException: source.readString() must not be null,定位代碼敲霍,發(fā)現(xiàn)原來(lái)是roomId這個(gè)變量為null俊马,即有的時(shí)候服務(wù)器會(huì)沒(méi)傳數(shù)據(jù)過(guò)來(lái),導(dǎo)致該字段為null肩杈,繼而在序列化的時(shí)候出現(xiàn)了異常柴我,導(dǎo)致問(wèn)題的出現(xiàn)。
找到了問(wèn)題原因扩然,那么我們就好解決了艘儒。
1、務(wù)必讓服務(wù)器傳該字段的數(shù)據(jù)夫偶,如果為null界睁,則傳默認(rèn)值
2、重寫(xiě)該屬性的getter/setter方法兵拢,當(dāng)為null時(shí)翻斟,傳一個(gè)默認(rèn)值
3、如果該字段沒(méi)有使用说铃,則去掉該屬性
這里我暫時(shí)沒(méi)有找到怎么重寫(xiě)數(shù)據(jù)類里變量的getter/setter方法访惜,所以我采用了方案3嘹履,待以后熟悉了,再更新更好的方法债热。