I have an app that uses ViewModel and MutableLiveData to bind live data to my UI. After hours westing my time! and review all sample on the internet I couldn't find the reason for the problem.
My activity:
public class DetailActivity extends DaggerAppCompatActivity {
ActivityStudentBinding mViewDataBinding;
MyModel myModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_student);
mViewDataBinding.setLifecycleOwner(this);
myModel = ViewModelProviders.of(this).get(MyModel.class);
mViewDataBinding.setViewmodel(myModel);
}
And my model class:
public class MyModel extends ViewModel
{
public MutableLiveData<StudentData.Student> student = new MutableLiveData<>();
public MyModel() {
this.student=student;
StudentData.Student student = new StudentData().getFirstStudent();
this.student.setValue(student);
}
}
And layout(I'vd cleaned extra codes here):
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data >
<variable
name="viewmodel"
type="googlearchitecturecomponents.ferdos.com.dagger211.detail.MyModel"/>
</data>
<TextView
android:text="@{viewmodel.student.id}" />
<TextView
android:text="@{viewmodel.student.family}" />
<TextView
android:text="@{viewmodel.student.id}"/>
</layout>
On runtime and on creating activity I get this error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{googlearchitecturecomponents.ferdos.com.dagger211/googlearchitecturecomponents.ferdos.com.dagger211.detail.DetailActivity}: java.lang.RuntimeException: Failed to call observer method--------- Stack trace ---------
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298) android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) android.app.ActivityThread.access$800(ActivityThread.java:144) android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) android.os.Handler.dispatchMessage(Handler.java:102) android.os.Looper.loop(Looper.java:135) android.app.ActivityThread.main(ActivityThread.java:5221) java.lang.reflect.Method.invoke(Native Method) java.lang.reflect.Method.invoke(Method.java:372) com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Please help me with this confusing error!!
viewmodel.student
returnsMutableLiveData<StudentData.Student>
which means you can't doviewmodel.student.id
so I assumeviewmodel.student.value.id
should work (not tested). – Pressor