【发布时间】:2017-01-04 06:51:32
【问题描述】:
我正在使用具有以下布局的 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 方法时遇到空指针异常。我可以调用 set 方法就好了,但是 get 返回一个空对象。
【问题讨论】:
标签: android data-binding android-databinding