question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

2.38: cannot instantiate ViewModel because of missing default constructor

See original GitHub issue

After update to Hilt 2.38, my app started to crash after start on instantiating ViewModel. Looks like default constructor is not generated. It can be kapt issue, but it worked fine on 2.37.

I was using lifecycle-viewmodel-ktx library on 2.3.1 version, updating it 2.4.0-alpha02 didn’t help

Stacktrace:

2021-07-22 14:08:49.465 8158-8158/fobo66.exchangecourcesbelarus.debug E/AndroidRuntime: FATAL EXCEPTION: main
    Process: fobo66.exchangecourcesbelarus.debug, PID: 8158
    java.lang.RuntimeException: Cannot create an instance of class fobo66.exchangecourcesbelarus.ui.MainViewModel
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:278)
        at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:112)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:54)
        at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:41)
        at fobo66.exchangecourcesbelarus.ui.MainFragment.getViewModel(MainFragment.kt:41)
        at fobo66.exchangecourcesbelarus.ui.MainFragment.setupSwipeRefreshLayout(MainFragment.kt:100)
        at fobo66.exchangecourcesbelarus.ui.MainFragment.onViewCreated(MainFragment.kt:72)
        at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2985)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:532)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:259)
        at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:113)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1327)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2757)
        at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:2693)
        at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2986)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:532)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:259)
        at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:113)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1327)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2757)
        at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2700)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:262)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:477)
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:246)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1455)
        at android.app.Activity.performStart(Activity.java:8076)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3658)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2202)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7829)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:982)
     Caused by: java.lang.InstantiationException: java.lang.Class<fobo66.exchangecourcesbelarus.ui.MainViewModel> has no zero argument constructor
        at java.lang.Class.newInstance(Native Method)
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219)
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:278) 
        at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:112) 
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185) 
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150) 
        at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:54) 
        at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:41) 
        at fobo66.exchangecourcesbelarus.ui.MainFragment.getViewModel(MainFragment.kt:41) 
        at fobo66.exchangecourcesbelarus.ui.MainFragment.setupSwipeRefreshLayout(MainFragment.kt:100) 
        at fobo66.exchangecourcesbelarus.ui.MainFragment.onViewCreated(MainFragment.kt:72) 
        at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2985) 
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:532) 
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:259) 
        at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:113) 
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1327) 
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2757) 
        at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:2693) 
        at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2986) 
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:532) 
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:259) 
        at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:113) 
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1327) 
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2757) 
        at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2700) 
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:262) 
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:477) 
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:246) 
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1455) 
        at android.app.Activity.performStart(Activity.java:8076) 
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3658) 
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221) 
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201) 
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2202) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loopOnce(Looper.java:201) 
        at android.os.Looper.loop(Looper.java:288) 
        at android.app.ActivityThread.main(ActivityThread.java:7829) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:982) 

MainFragment.kt where it happens:

@AndroidEntryPoint
class MainFragment : Fragment() {

  private val viewModel: MainViewModel by viewModels()
  // ...

MainViewModel.kt:

@HiltViewModel
class MainViewModel @Inject constructor(
  private val refreshExchangeRates: RefreshExchangeRates,
  private val loadExchangeRates: LoadExchangeRates,
  private val copyCurrencyRateToClipboard: CopyCurrencyRateToClipboard,
  private val findBankOnMap: FindBankOnMap
) : ViewModel() {

  val bestCurrencyRates: Flow<List<BestCurrencyRate>>
    get() = loadExchangeRates.execute()

  val errors: SharedFlow<Unit>
    get() = _errors

  val progress: SharedFlow<Boolean>
    get() = _progress

  private val _errors = MutableSharedFlow<Unit>()
  private val _progress = MutableSharedFlow<Boolean>()

  fun findBankOnMap(bankName: CharSequence): Intent? {
    return findBankOnMap.execute(bankName)
  }

  fun refreshExchangeRates() =
    viewModelScope.launch {
      try {
        showProgress()
        refreshExchangeRates.execute(LocalDateTime.now())
        hideProgress()
      } catch (e: CurrencyRatesLoadFailedException) {
        Timber.e(e, "Error happened when refreshing currency rates")
        _errors.emit(Unit)
      } finally {
        hideProgress()
      }
    }

  fun copyCurrencyRateToClipboard(currencyName: CharSequence, currencyValue: CharSequence) {
    copyCurrencyRateToClipboard.execute(currencyName, currencyValue)
  }

  private suspend fun showProgress() {
    _progress.emit(true)
  }

  fun hideProgress() {
    viewModelScope.launch {
      _progress.emit(false)
    }
  }
}

Dependencies of MainViewModel are provided here:

@Module
@InstallIn(ViewModelComponent::class)
abstract class CurrencyRatesModule {

  @Binds
  abstract fun provideRefreshExchangeRates(
    refreshExchangeRatesImpl: RefreshExchangeRatesImpl
  ): RefreshExchangeRates

  @Binds
  abstract fun provideLoadExchangeRates(
    loadExchangeRatesImpl: LoadExchangeRatesImpl
  ): LoadExchangeRates

  @Binds
  abstract fun provideCopyCurrencyRateToClipboard(
    copyCurrencyRateToClipboardImpl: CopyCurrencyRateToClipboardImpl
  ): CopyCurrencyRateToClipboard

  @Binds
  abstract fun provideFindBankOnMap(
    findBankOnMapImpl: FindBankOnMapImpl
  ): FindBankOnMap
}

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:10
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
danysantiagocommented, Aug 6, 2021

@fobo66, I took a look at your project and your PR and the issue is that you compose functions where you are trying to get the ViewModel from are inside a Navigation graph. Therefore the compose function viewModel() will not use the Activity’s ViewModelFactory and instead will use the closest LocalViewModelStoreOwner which will be a NavGraphEntry.

If you want to use Hilt injected ViewModels use the androidx.hilt:hilt-navigation-compose artifact and the hiltViewModel() method as described here: https://developer.android.com/jetpack/compose/libraries#hilt-navigation

0reactions
fobo66commented, Aug 6, 2021

@danysantiago Oh, somehow I missed this, probably thinking that it’s the same thing as androidx.lifecycle.viewmodel.compose.viewModel. Thanks, it works fine now. Sorry for bothering

Read more comments on GitHub >

github_iconTop Results From Across the Web

Hilt 2.38 @AndroidEntryPoint/@HiltAndroidApp transform ...
A bug in 2.38 is causing the bytecode transform to miss non-test code when ... 2.38: cannot instantiate ViewModel because of missing default...
Read more >
HiltViewModel: Cannot create an instance of class
I've seen this happens when the Fragment/Activity that is using the ViewModel is missing the @AndroidEntryPoint annotation, for instance:
Read more >
Dependency injection with Hilt | Android Developers
ViewModel. ViewModel overview · Create ViewModels with dependencies · ViewModel Scoping APIs · Saved State module for ViewModel.
Read more >
Dagger Hilt — ViewModelClass has no zero argument ...
Missing @ViewModelInject on ViewModel constructor (now deprecated). Another frequent thing we forget. Instead of just a regular constructor with parameters, ...
Read more >
The practical guide – Part 4: Dependency injection with Hilt
So, what is the fix? The fix is very obvious: instead of letting A create B, we pass B through the constructor/method/parameter of...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found