Architecture-components-samples: What will case "Can't access ViewModels from onDestroy" and how to solve it gracefully?

Created on 19 Dec 2017  路  5Comments  路  Source: android/architecture-components-samples

java.lang.RuntimeException: Unable to destroy activity {xxxxxx}: java.lang.IllegalStateException: Can't access ViewModels from onDestroy

Most helpful comment

why not

class XxxAdapter {
      public XxxAdapter(XxxViewmodel vm) {

      }
}

All 5 comments

I've seen this issue when using ViewModels inside of a RecyclerView holder while backgrounding/foregrounding an app. Haven't figured out how to solve it yet though.

java.lang.IllegalStateException: Can't access ViewModels from onDestroy at android.arch.lifecycle.HolderFragment$HolderFragmentManager.findHolderFragment(HolderFragment.java:139) at android.arch.lifecycle.HolderFragment$HolderFragmentManager.holderFragmentFor(HolderFragment.java:158) at android.arch.lifecycle.HolderFragment.holderFragmentFor(HolderFragment.java:84) at android.arch.lifecycle.ViewModelStores.of(ViewModelStores.java:47) at android.arch.lifecycle.ViewModelProviders.of(ViewModelProviders.java:124) at com.example.adapter.MyViewHolder.<init>(MyViewHolder.java:111)

@AndrewWestberg

Why call ViewModelproviders.of(activity or fragment).get(XxxxViewModel.class) in RecyclerView's adapter?

why not

class XxxAdapter {
      public XxxAdapter(XxxViewmodel vm) {

      }
}

This doesn't seem to be an issue with the samples. You can file an issue against Lifecycle on the issue tracker if you're still having an issue.

Was this page helpful?
0 / 5 - 0 ratings