Parceler does not work in android x.
You can use this:
class ExParcelable @JvmOverloads constructor(data: Any? = null) : Parcelable {
var cls: String? = null
var json: String? = null
init {
if (data is Parcel) {
cls = data.readString()
json = data.readString()
} else {
cls = data?.let { it::class.java }?.canonicalName
json = Gson().toJson(data)
}
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(cls)
parcel.writeString(json)
}
override fun describeContents(): Int {
return 0
}
fun value(): Any? {
return Gson().fromJson(this.json, Class.forName(this.cls))
}
companion object CREATOR : Creator<ExParcelable> {
override fun createFromParcel(parcel: Parcel): ExParcelable {
return ExParcelable(parcel)
}
override fun newArray(size: Int): Array<ExParcelable?> {
return arrayOfNulls(size)
}
}
}
and :
inline fun <reified T : Any?> Intent.extra(key: String): T? {
var value = extras?.get(key)
if (value is ExParcelable) {
value = value.value()
} else if (T::class == Uri::class) {
if (value is String) {
value = value.toUri()
}
} else if (T::class == String::class) {
if (value is Uri) {
value = value.toString()
}
}
return value as T?
}
inline fun <reified T : Any?> Intent.extra(key: String, value: T?) {
when (value) {
null -> {
// no op
}
is Uri -> putExtra(key, value.toString())
is Boolean -> putExtra(key, value)
is BooleanArray -> putExtra(key, value)
is Byte -> putExtra(key, value)
is ByteArray -> putExtra(key, value)
is Char -> putExtra(key, value)
is CharArray -> putExtra(key, value)
is Short -> putExtra(key, value)
is ShortArray -> putExtra(key, value)
is Int -> putExtra(key, value)
is IntArray -> putExtra(key, value)
is Long -> putExtra(key, value)
is LongArray -> putExtra(key, value)
is Float -> putExtra(key, value)
is FloatArray -> putExtra(key, value)
is Double -> putExtra(key, value)
is DoubleArray -> putExtra(key, value)
is Date -> putExtra(key, value)
is Bundle -> putExtra(key, value)
is Parcelable -> putExtra(key, value)
is Serializable -> putExtra(key, value)
is RealmObject -> putExtra(key, ExParcelable(value.get()))
else -> putExtra(key, ExParcelable(value))
}
}
and use it like this:
new Intent().apply{
extra("test", realmObject)
}
and :
intent.extra("test")