I have a ViewModel like that:
public class LoginViewModel {
public final ObservableField<String> email = new ObservableField<>();
public final ObservableField<String> password = new ObservableField<>();
public LoginViewModel() {
I have two editText and one button in my View:
<EditText
android:id="@+id/password"
android:text="@={login.email}"/>
<EditText
android:id="@+id/password"
android:text="@={login.password}"/>
<Button android:onClick="onLoginClick"/>
In my activity would like to print the two edittext value when button clicked, something like that:
LoginActivityBinding loginActivityBinding = DataBindingUtil.setContentView(this, R.layout.activity_login);
Log.e("password", ""+loginActivityBinding.getLogin().password.get());
I get a Nullpointer Exception, how should I modify my code to get the values.
When you instantiate an ObservableField, the default value is null. When the EditText modifies the value (even if empty), it will be set to a non-null value. However, until then, it is null.
It is easy to fix this by giving your fields a non-null initial value:
public final ObservableField<String> email = new ObservableField<>("");
public final ObservableField<String> password = new ObservableField<>("");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With