Caused by java.lang.IllegalStateException: Can't create ViewModelProvider for detached fragment

If you're using a viewpager, be sure that the corresponding fragment is actually attached to its activity (this is what the error tries to tell you). It might happen that the fragment is not visible, thus it's not attached (depending on how the view pager was configured).

a quick&dirty fix:

public void search(String query) {

    if(!isAdded()) return; //<---- returns if the fragment is not attached

    query = "%" + query + "%";
    if (myListViewModel == null) {
        myListViewModel = ViewModelProviders.of(this, viewModelFactory).get(MyListViewModel.class);
    }
    if (myListViewModel.mList != null && myListViewModel.mList.hasActiveObservers()) {
        myListViewModel.mList.removeObservers(this);
    }
    myListViewModel.getFilteredList(query).observe(this, mainObserver);
}

However, you should re-investigate in your architecture, because those checks often imply some other code smells. When you're working with the new Android Architecture Patterns, there should be no need of this check as the lifecycle pattern handles all this for you: https://developer.android.com/topic/libraries/architecture/lifecycle

So, basically, you should not directly call any function of a fragment directly, instead call the corresponding business logic, which notifies the fragment to update its views.


Since the error is that the fragment is not attached yet, it needs to be done when we are sure the fragment is actually attached. Its a good way of doing this; by putting the code inside the override method onAttach

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    myListViewModel = ViewModelProviders.of(this, viewModelFactory).get(MyListViewModel.class);
}