Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Edittext value with databinding?

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.

like image 275
XXX Avatar asked Feb 07 '17 08:02

XXX


1 Answers

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<>("");
like image 81
George Mount Avatar answered Sep 21 '22 12:09

George Mount