Android数据绑定支持最酷的功能之一是它还为View设置了ID字段.这样可以整理代码库,因为不需要字段或findViewById()调用.
但问题是绑定实例只能通过bind()调用来检索,该调用往往会调度绑定.当异步接收数据并且通常抛出NullPointerException时,这很糟糕.
可以检索带有View字段的绑定实例减去实际的数据绑定过程吗?
堆栈跟踪:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
at com.app.android.databinding.ActivityRestaurantDetailsBinding.executeBindings(ActivityRestaurantDetailsBinding.java:381)
at android.databinding.ViewDataBinding.executePendingBindings(ViewDataBinding.java:350)
at android.databinding.ViewDataBinding$6.run(ViewDataBinding.java:167)
at android.databinding.ViewDataBinding$5.onViewAttachedToWindow(ViewDataBinding.java:137)
at android.view.View.dispatchAttachedToWindow(View.java:14525)
最佳答案
这似乎没有意义,数据绑定将忽略空变量,因此不应该抛出空指针,也就是说,我相信,它是其最受推崇的功能之一.如果你需要在异步调用等之后修改变量,你可以使用dataBinding.executePendingBindings()
从the docs起
The generated binding class will have a setter and getter for each of the described variables. The variables will take the default Java values until the setter is called — null for reference types,0 for int,false for boolean,etc.
和
Generated data binding code automatically checks for nulls and avoid null pointer exceptions. For example,in the expression @{user.name},if user is null,user.name will be assigned its default value (null). If you were referencing user.age,where age is an int,then it would default to 0.