【问题标题】:Android DataBinding setVariable() followed by getVariable() call returns nullAndroid DataBinding setVariable() 后跟 getVariable() 调用返回 null
【发布时间】: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


    【解决方案1】:

    事实证明,如果布局中没有引用变量,那么生成的 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 变量,或者使用不同的模式来观察变化。

    【讨论】:

    • 或者,创建一个跟踪 TransactionViewModel 的绑定的子类。
    猜你喜欢
    • 2018-11-27
    • 1970-01-01
    • 2010-10-15
    • 2016-04-03
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    相关资源
    最近更新 更多