BVtp
BVtp

Reputation: 2480

unable to create ViewModel - my_package.App cannot be cast to android.arch.lifecycle.LifecycleOwner

I'm trying to create a ViewModel in MainActivity, which observes to some data changes in some singleton component. The goal is to use that ViewModel in a few fragments of this activity. But so far even without involving the fragment yet it doesn't work. The app gets stuck at launch, printing :

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 

the problem seems to be in the line : MyCustomSingletonComponent.getInstance().getSomeDataLiveData().observe......

The Code :

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);

        ....
    }           
}

Upvotes: 0

Views: 1709

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007322

First, an Application is not a LifecycleOwner, so you cannot pass it to observe() on a LiveData. Activities and fragments are standard lifecycle owners.

Second, IMHO, a ViewModel should not be observing anything. The thing that uses the ViewModel does the observing. MyViewModel might hold onto the LiveData, but then MainActivity is the one that observes.

Upvotes: 1

Related Questions