簡體   English   中英

Android DataBinding setVariable()后跟getVariable()調用返回null

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM