无法创建ViewModel-无法将my_package.App强制转换为android.arch.lifecycle.LifecycleOwner

时间:2018-08-26 13:11:07

标签: android mvvm android-livedata

我正在尝试在MainActivity中创建一个ViewModel,它观察某些单例组件中的某些数据变化。目标是在该活动的一些片段中使用该ViewModel。但是到目前为止,即使不涉及片段,它也不起作用。该应用在启动时卡住,无法打印:

java.lang.RuntimeException: Unable to start activity ComponentInfo{my_package.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class my_package.MyViewModel

my_package.App cannot be cast to android.arch.lifecycle.LifecycleOwner 

问题似乎出在行中:MyCustomSingletonComponent.getInstance().getSomeDataLiveData().observe......

代码:

public class MyCustomSingletonComponent
{
    public MutableLiveData<CustomClass> someData = new MutableLiveData<>(); 

    private static final MyCustomSingletonComponent instance = new MyCustomSingletonComponent();

    private MyCustomSingletonComponent() {
        someData = new MutableLiveData<>();
    }

    public static MyCustomSingletonComponent getInstance() {
        return instance;
    }

    public LiveData<CustomClass> getDataLiveData()
    {
        return someData;
    }

}


public class MyViewModel extends AndroidViewModel {

    public MyViewModel(@NonNull Application application) 
    {
        super(application);

        MyCustomSingletonComponent.getInstance().getSomeDataLiveData().observe(getApplication(), myData -> {
            ...  
        });
    }           
}

public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);

        ....
    }           
}

1 个答案:

答案 0 :(得分:1)

首先,Application不是LifecycleOwner,因此您不能将其传递给observe()上的LiveData。活动和片段是标准的生命周期所有者。

第二,恕我直言,ViewModel不应观察任何内容。使用ViewModel的事物进行观察。 MyViewModel可能会紧紧抓住LiveData,但是MainActivity就是观察到的那个。