
[英]NullPointerException received when calling Bundle.getParcelable
[英]why the different parceable get instantiated when getParcelable is on different one
在 android 中具有一些可打包的类
@Parcelize
class ParcelableClassA(private val member: Int) : IAParcelable {
init {
Log.e("+++", "+++ ParcelableClassA::init{}, this: $this")
}
@Parcelize
class ParcelableClassB(private val member: String) : IBParcelable {
init {
Log.e("+++", "+++ ParcelableClassB::init{}, this: $this")
}
在某些地方它被实例化并放入一个包中以创建一个活动。
Intent(context, TheActivity::class.java).apply {
val bundle = Bundle()
bundle.putParcelable(EXTRAS_CLASS_A, ParcelableClassA(1))
bundle.putParcelable(EXTRAS_CLASS_B, ParcelableClassB("B")
...
putExtras(bundle)
context.startActivity(this)
}
在活动 class 中:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val classA = intent.extras?.getParcelable(EXTRAS_CLASS_A) as? IAParcelable
val classB = intent.extras?.getParcelable(EXTRAS_CLASS_B) as? IBParcelable
}
原以为只有一个打印输出"+++ ParcelableClassA::init{}, this: $this"
但实际上看到创建了 ParcelableClassA 的两个实例,一个在
intent.extras?.getParcelable(EXTRAS_CLASS_A)
另一个也发生在
intent.extras?.getParcelable(EXTRAS_CLASS_B)
叫做。 所以 ParcelableClassA::init{} 和 ParcelableClassB::init{} 都被调用了两次。
如果额外放入的数据越多,调用的 ParcelableClassA 的实例化就越多,这只是浪费。
这是预期的行为还是这里的做法不正确?
更新:似乎在BaseBundle中,如果在 unparcel() 中并且 mParcelledData 不是 null 它将有这种行为。 但不确定为什么会发生。 如果逐步调试它似乎 mParcelledData 总是 null 并且没有这个问题,但是如果只是运行它就会显示这个问题。
void unparcel() {
synchronized (this) {
final Parcel source = mParcelledData;
if (source != null) {
initializeFromParcelLocked(source, /*recycleParcel=*/ true, mParcelledByNative);
} else {
if (DEBUG) {
Log.d(TAG, "unparcel "
+ Integer.toHexString(System.identityHashCode(this))
+ ": no parcelled data");
}
}
}
}
看起来像使用intent.extra? 导致问题。
如果更改为
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var bundle = intent.extras
val classA = bundle?.getParcelable(EXTRAS_CLASS_A) as? IAParcelable
val classB = bundle?.getParcelable(EXTRAS_CLASS_B) as? IBParcelable
}
似乎没有看到dups。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.