[英]Android DataBinding setVariable() followed by getVariable() call returns null
我正在使用具有以下布局的DataBinding。 我正在绑定对象上调用setViewModel()方法。 如果我立即调用binding.getViewModel(),它将返回null。 见下面的代码:
布局:
<layout>
<data>
<variable
name="viewModel"
type="reyes.r.christopher.spenderbender.viewmodel.TransactionViewModel"/>
</data>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/viewExpenseListTable"
android:shrinkColumns="*"
android:stretchColumns="*"
>
</TableLayout>
</ScrollView>
</layout>
活动:
public class ViewExpenseListActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityViewExpenseListBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_view_expense_list);
LocalDatabaseHandler dbh = new LocalDatabaseHandler(this);
TransactionViewModel viewModel = new TransactionViewModel(dbh);
binding.setViewModel(viewModel);
if ( BuildConfig.DEBUG ) {
if (viewModel == null) {
throw new AssertionError("Somehow viewModel is null...");
}
if(binding.getViewModel() == null) {
// This Assertion is always thrown
throw new AssertionError("viewModel is not null, but wasn't set in the binding");
}
}
// Throws NullPointerException
binding.getViewModel().loadAllExpenses();
}
...
}
您可能会注意到我没有在布局中的任何位置使用变量。 每当新行添加到数据库时,我都试图以编程方式用数据库中的值替换表中的行。 这就是我需要从绑定中获取viewModel的原因。
PS:我发现了类似的问题: Android Databinding Adapter Null Pointer Exception 。 当他们调用set方法而不是get方法时,这个人得到了Null Pointer Exception。 我可以调用set方法,但get返回一个null对象。
事实证明,如果布局中未引用变量,则不会生成生成的setter和getter。
我决定发布这个以防万一其他人在将来有类似的问题,但我在调查生成的文件时发现了这一点。 以下是生成的ActivityViewExpenseListBinding类中getViewModel()和setViewModel()方法的外观:
public void setViewModel(reyes.r.christopher.spenderbender.viewmodel.TransactionViewModel viewModel) {
// not used, ignore
}
public reyes.r.christopher.spenderbender.viewmodel.TransactionViewModel getViewModel() {
return null;
}
我需要从布局中引用viewModel变量,或者使用不同的模式来观察更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.