Cannot create an instance of class ViewModel
Asked Answered
C

36

160

I am trying to write a sample app using Android architecture components and but even after trying for days I could not get it to work. It gives me the above exception.

Lifecycle owner:-

public class MainActivity extends LifecycleActivity {

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = findViewById(R.id.tv_user);
        PostViewModel viewModel = ViewModelProviders.of(this).get(PostViewModel.class);
        viewModel.loadPosts();
        viewModel.getPost().observe(this, new Observer<Post>() {
            @Override
            public void onChanged(@Nullable Post post) {
                if(post != null) {
                    textView.setText(post.toString());
                }
            }
        });
    }
}

ViewModel:-

public class PostViewModel extends ViewModel {
    private MediatorLiveData<Post> post;
    private PostRepository postRepo;

    PostViewModel() {
        post = new MediatorLiveData<>();
        postRepo = new PostRepository();
    }

    public LiveData<Post> loadPosts() {
        post.addSource(postRepo.getPost(),
                post -> this.post.setValue(post)
        );
        return post;
    }

    @NonNull
    public LiveData<Post> getPost() {
        return post;
    }
}
Corinnacorinne answered 9/7, 2017 at 15:30 Comment(1)
If you're using Hilt and Compose Navigation, check this one: https://mcmap.net/q/152065/-cannot-create-viewmodel-from-composalbe-functionFroemming
K
159

Make your constructor public.

Kendyl answered 9/7, 2017 at 15:33 Comment(7)
However strangely Android studio gives a warning after making constructor public saying "Access can be package-private" .Corinnacorinne
@ParagKadam: Android Studio does not know that the lifecycle components need the constructor to be public. Android Studio only goes by what it can see through explicit code references.Kendyl
Still getting the error in a fragment, both class and constructor are already public.Chancemedley
My constructor is public, but I received this error: Caused by java.lang.RuntimeException: Cannot create an instance of class com.randa.android.model.search.SearchActivityViewModel at android.arch.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:153) at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:210) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102) at com.randa.android.Ellis
Funny thing is it works in debug mode but crashes when the app is compiled in release mode.Plantagenet
Both constructor and the class need to be public !Joannejoannes
And the class must be static if it's a nested class in your Activity.Faust
L
269

if you are using Hilt, ensure your activity/fragment is having @AndroidEntryPoint annotation

Levite answered 18/8, 2020 at 14:55 Comment(11)
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From ReviewDisembowel
well @AndriiOmelchenko, have you tried Hilt with injection in viewModel constructor? because I believe this is an honest mistake that most developers will make that will cause Cannot create an instance of class ViewModel crash during run-time.Levite
I'm using Dagger Hilt, and that answer saved me a lot of time, thanks!Comminate
I always make the same mistake and find myself here. Thank you.Acerate
same here. I always always make the same mistake. wondering around then always find the answer hereRisarise
This was an answer for me too. I wonder why some are so quick to give negative unhelpful views if they don;t have knowledge of a domain. On another note, Fragments were working at some point without the @AndroidEntryPoint. The viewmodel jammed when i made it a little more complicated, with an injected argument in the constructor.Lyssa
Even after putting @AndroidEntryPoin I'm getting java.lang.RuntimeException: Cannot create an instance of class ViewModelDareen
In feature modules, the way that modules usually depend on each other is inverted. Therefore, Hilt cannot process annotations in feature modules. You must use Dagger to perform dependency injection in your feature modules.Overwhelming
Latest @HiltViewModel on top of your viewModelAbundant
top!!! if u need inject to viewmodel add @AndroidEntryPoint in this fragment!Lungi
@SamsadCV if this doesn't fix your problem, check your ViewModel-constructor params. If you have anything in there that isn't provided by a dagger/hilt-@Module in your project, then add a @Provides-method in that module. If you try to inject another ViewModel into your ViewModel, you have to create a ViewModelFactory with all needed constructor-params and method create to instantiate your ViewModel there. You cannot annotate that ViewModel with @HiltViewModel in that case, AFAIK.Throes
K
159

Make your constructor public.

Kendyl answered 9/7, 2017 at 15:33 Comment(7)
However strangely Android studio gives a warning after making constructor public saying "Access can be package-private" .Corinnacorinne
@ParagKadam: Android Studio does not know that the lifecycle components need the constructor to be public. Android Studio only goes by what it can see through explicit code references.Kendyl
Still getting the error in a fragment, both class and constructor are already public.Chancemedley
My constructor is public, but I received this error: Caused by java.lang.RuntimeException: Cannot create an instance of class com.randa.android.model.search.SearchActivityViewModel at android.arch.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:153) at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:210) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102) at com.randa.android.Ellis
Funny thing is it works in debug mode but crashes when the app is compiled in release mode.Plantagenet
Both constructor and the class need to be public !Joannejoannes
And the class must be static if it's a nested class in your Activity.Faust
H
30

DaggerHilt can also be the reason, If you are using it make sure your activity/fragment is having @AndroidEntryPoint annotation on it.

Hurdle answered 18/12, 2020 at 19:9 Comment(0)
S
28

If you are using Kotlin make sure to replace any annotationProcessor in build.gradle with kapt.

Like:

annotationProcessor "android.arch.persistence.room:compiler:$rootProject.roomVersion"

Will become

kapt "android.arch.persistence.room:compiler:$rootProject.roomVersion"

and add

apply plugin: 'kotlin-kapt' on top of the buidl.gradle file.

Annotation Processing with Kotlin

Syndicate answered 29/7, 2018 at 5:12 Comment(4)
It fixed my problem. It may not be the right answer for java, but it is correct for "Cannot create an instance of class ViewModel in Kotlin"Matthias
@Matthias I posted the answer for the exact same reason because it took me quite a while to understand this issue. But ppl are not gentle and keep downvoting lol even though I have clearly mentioned if you are using kotlin.Syndicate
It saved me, i hate this android logger, i got an exception about something and the reason is actually something elseDemodena
@Demodena maybe you should use "log filters" in Android Studio.Jerome
D
24

For people using Jetpack Compose, Navigation and Hilt

Make sure to use the hiltNavGraphViewModel instead of viewModel.

This is provided by androidx.hilt:hilt-navigation-compose dependency.

More details in the docs.

Deodorant answered 19/4, 2021 at 20:5 Comment(2)
Thank you! I used viewModel and got error java.lang.RuntimeException: Cannot create an instance of class my.app.MyViewModel. But after using hiltViewModel, as stated in the documentation, everything worked!Steatopygia
I wasted quite some time on this error. Still valid in 2023, luckily docs show how to get ViewModel in NavHost. Thanks!Shipment
I
21

Make sure your ViewModel has constructor with only one parameter i.e. Application.

example:

public YourViewModel(Application application) {
    super(application);
    ...
Idolla answered 21/7, 2018 at 18:52 Comment(3)
Thanks, i created constructor of ViewModel Class get two arguments, I deleted one and good result.Pettis
yes it have only one parameter but its still crashingBellboy
Why can ViewModel only have one constr. parameter?Traveled
M
21

Add @HiltViewModel on top of your viewModel .

Maribeth answered 31/8, 2021 at 6:59 Comment(0)
P
15

There are few reason to throw the exception . I have mention some of them..

  1. Make sure your view Model class is public

  2. Make sure your view model class constructor is public

  3. Make sure you have added the dependency in your gradle file for lifecycle also if you use room and other libraries you have added ..

  4. if you create object any other dependent class in your view model class constructor . Other class can throw error to create the instance of viewModel

Pinta answered 7/11, 2018 at 6:22 Comment(1)
Great for the 4th point!!! It really solves me after finding your step by step solution.Ciapha
S
13

I had this problem following google's roomdb CodeLab. Solution was changing the following.

Edited

Add the following Build dependencies to Gradle file (as of 2/22/2020)

implementation 'androidx.fragment:fragment:1.2.2'
implementation 'androidx.lifecycle:lifecycle-process:2.2.0'
implementation 'androidx.lifecycle:lifecycle-service:2.2.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:2.2.0'
annotationProcessor 'androidx.lifecycle:lifecycle-compiler:2.2.0'

Imports within the fragment

import androidx.lifecycle.ViewModelProvider;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;

Creating the viewModel. Add one of the following methods.

Note: I'v seen this done many ways. I believe the correct way is using getDefaultViewModelProviderFactory(). But I have been using requireActivity().

 new ViewModelProvider(requireActivity(),getDefaultViewModelProviderFactory()).get(YourViewModel.class);

|

 new ViewModelProvider(requireActivity()).get(YourViewModel.class);

          

ViewModelProvider Docs

Deprecated

implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0-rc01'
annotationProcessor 'androidx.lifecycle:lifecycle-compiler:2.2.0-rc01'
Severini answered 6/1, 2020 at 2:0 Comment(3)
The latest android lifecycle documentation says that the lifecycle-extensions dependency is now deprecated developer.android.com/jetpack/androidx/releases/lifecycle# However, if I remove that dependency from the gradle file I am getting the cannot create an instance of class viewmodel error when I start my app. I tried adding all of the other dependencies listed as current, even the optional ones, but it won't work without the lifecycle-extensions dependency. For now, I have to keep the deprecated dependency. I am still trying to find why it fails without this dependency.Presentiment
Good info @Presentiment , I updated my answer based on your comment.Severini
Thanks for this answer, I had the same issue following roomdb CodeLab, the only thing I had to add was implementation 'androidx.fragment:fragment:1.2.5'Lastditch
A
7

If you are use Hilt, your activity or fragment need @AndroidEntryPoint annotation and also view model need @HiltViewModel annotation.

Apiculture answered 9/5, 2023 at 6:25 Comment(0)
T
6

It was not completely obvious to me, but when getting this error I resolved it by creating a public constructor. My constructor was derived from the Android Developer examples and contained the Repository as a parameter. Creating an additional constructor that was empty with no params and having it public solved the issue.

i.e., in your case

public PostViewModel() {}

Trysail answered 3/1, 2018 at 1:49 Comment(3)
What if we need to pass parameters to ViewModel??Traveled
You can create an additional constructor for that one, but having a NoArgsConstructor is what is needed to solve this issue.Trysail
Where is the official documentation proving this?Traveled
P
5

Make the class and constructor public it solved my problem .

Polinski answered 21/5, 2018 at 7:19 Comment(0)
M
5

Extend AndroidViewModel from your ViewModel class.

public class YourViewModel extends AndroidViewModel {

    public YourViewModel(Application application) {
        super(application);

        //Todo: ...
    }

}
Midlands answered 19/4, 2019 at 20:54 Comment(0)
C
5

If you used viewmodel inside your activity check that your activity extends "DaggerAppCompatActivity" or not

For instance

public class UserComments extends AppCompatActivity 

change this to

public class UserComments extends DaggerAppCompatActivity
Catima answered 17/5, 2019 at 18:11 Comment(0)
D
4

In my case, the reason was that I was trying to get a shared instance of the ViewModel in my fragment too soon - before the activity was created. What happens when the application is restoring its state after being killed.

Preconditions:

  1. My ViewModel has a public constructor.
  2. My ViewModel has multiple arguments. But this is absolutely fine as I use ViewModelFactory to construct the ViewModel.
  3. My Fragment and Activity shares the same instance of the ViewModel. In other words: Activity creates the ViewModel and the fragment receives the same instance later.

Code in activity:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    //factory is constructed using Dagger
    val factory = App.get().components().appComponent.getMapViewModelFactory() 
    //activity creates the instance of MapViewModel
    viewModel = ViewModelProviders.of(this, factory)[MapViewModel::class.java]
}

Code in fragment:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    //fragment receives the instance of MapViewModel
    viewModel = ViewModelProviders.of(activity!!)[MapViewModel::class.java]
    ...
}

When I open the app for the first time, everything works fine: activity creates an instance of ViewModel; I open Fragment, which gets the instance of ViewModel. But when the application is trying to restore its state after being killed, first it calls the body of onCreate of the Fragment and then the body of onCreate of the Activity. At that point, the fragment can't get the ViewModel as Activity had not created it yet.

Solution 1: Move the code when the fragment gets the ViewModel from onCreate to onViewCreated. This is fine as I observe all live data in onViewCreated as well.

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    viewModel = activity?.run { ViewModelProviders.of(this)[MapViewModel::class.java] } ?: throw Exception("Invalid Activity")

    viewModel.getSurveyDateLiveData().observe(viewLifecycleOwner, Observer<String> { dateTextView.text = it })
    ...
}

Solution 2: Create the instance of ViewModel in Activity.onCreate before super.onCreate is called. In this case, you can get the ViewModel in your fragment's onCreate.

override fun onCreate(savedInstanceState: Bundle?) {
    
    val factory = App.get().components().appComponent.getMapViewModelFactory()
    viewModel = ViewModelProviders.of(this, factory)[MapViewModel::class.java]
    
    super.onCreate(savedInstanceState)
    Timber.d("cc: onCreate: $this ")
}

Solution 3:

If you are injecting repository instance in your ViewModel, Check that you are not using @Inject constructor(...): ViewModel() to inject your repository, but rather **@ViewModelInject constructor(...): ViewModel()**

Drawshave answered 21/11, 2019 at 7:47 Comment(0)
Z
3
  1. Mostly, Solution is making Class and Constructor Public as the other answers
  2. It may also be a runtime error, check the Logcat Error Logs if there are multiple causes listed.
Zebapda answered 23/12, 2018 at 23:55 Comment(1)
Yes it is very important the the class is also public.Backwoods
W
3

If you are using Hilt then don't forget to add these four dependencies.

    implementation "com.google.dagger:hilt-android:2.28-alpha"
    kapt "com.google.dagger:hilt-android-compiler:2.28-alpha"
    implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha01'
    kapt "androidx.hilt:hilt-compiler:1.0.0-alpha01"

Note:- If any of these dependencies are missing you will get Cannot create an instance of class ViewModel error

Whitley answered 25/6, 2020 at 20:54 Comment(4)
I have all 4 still I am getting that error. I have 2 view model 1 on splash works well 1 on home gives this error -__0 . Although later is copiedPriapitis
This answer helped me. I was missing kapt "androidx.hilt:hilt-compiler:1.0.0-alpha01". That alone prevented my ViewModel (with parameters in its constructor, no ViewModelFactory) from being created.Twana
you're my hero. you save my time, thank youKarlotta
@Karlotta you can upvote your hero's answer.Whitley
D
3

I fixed the same problem by doing this.

Note:- I am using Dagger hilt, Room database, MVVM, Data binding

Added the annotation.

class AlertViewModel
@Inject
constructor(private val userRepository: AlertRepository) : ViewModel(){
    val getList:LiveData<List<Alert>> get() =
        userRepository.getList.flowOn(Dispatchers.Main)
            .asLiveData(context = viewModelScope.coroutineContext)

    fun insert(user:Alert){
        viewModelScope.launch {
            userRepository.insert(user)
        }
    }
}

To

@HiltViewModel // Added this annotation
class AlertViewModel
@Inject
constructor(private val userRepository: AlertRepository) : ViewModel(){
    val getList:LiveData<List<Alert>> get() =
        userRepository.getList.flowOn(Dispatchers.Main)
            .asLiveData(context = viewModelScope.coroutineContext)

    fun insert(user:Alert){
        viewModelScope.launch {
            userRepository.insert(user)
        }
    }
}
Dump answered 28/10, 2021 at 16:34 Comment(0)
S
2

I got this after migrating to AndroidX.

There's a bug in androidx.lifecycle:lifecycle-viewmodel:2.0.0-beta01 where Proguard removes the constructor.

https://issuetracker.google.com/issues/112230489

Fix by upgrading to 2.0.0, and remember to update your proguard rules if needed.

My error message looked like this:

java.lang.RuntimeException: Cannot create an instance of class my.custom.viewmodel.CustomViewModel
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:202)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103)
......
Caused by: java.lang.NoSuchMethodException: <init> [class android.app.Application]
at java.lang.Class.getConstructor0(Class.java:2204)
at java.lang.Class.getConstructor(Class.java:1683)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:200)
... 34 more


  androidx.test.espresso.PerformException: Error performing 'single click - At Coordinates: 539, 1167 and precision: 16, 16' on view 'with id: my.test:id/button_return_to_main_menu'.
at androidx.test.espresso.PerformException$Builder.build(PerformException.java:82)
at androidx.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:79)
.....
Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{my.custom.domain.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class my.custom.viewmodel.CustomViewModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
Sputnik answered 15/3, 2019 at 11:14 Comment(0)
M
2

if your PostViewModel class is an inner class, make sure its public and static

Metatarsal answered 1/7, 2019 at 9:58 Comment(0)
T
2

Please add below code. It worked for me

val binding = FragmentLayoutBinding.inflate(inflater, container, false)

val viewModel = ViewModelProvider(
            requireActivity(),
            defaultViewModelProviderFactory
            ).get(MainViewModel::class.java)
Threescore answered 13/8, 2020 at 15:35 Comment(2)
and using -> @AndroidEntryPoint on fragment/activitySnowshed
@umitx if you are using Hilt only than we have to do this in ActivityThreescore
A
2

If you face this issue in Kotlin Dagger Hilt even after @HiltViewModel and using @Inject, make sure you have updated all hilt dependencies.

Apochromatic answered 5/5, 2021 at 7:22 Comment(0)
L
1

In my case I needed to use a ListItemViewModelFactory to pass in a parameter to my view model.

Laden answered 24/7, 2019 at 21:7 Comment(1)
Yes. We have to create YourViewModelFactory(private val param: String) : ViewModelProvider.Factory to have a parameter inside ViewModel.Pediform
T
1

In my case, it was gradle a dependencies problem.

If you are using Livedata,,

build.gradle(Module.app)

not

implementation 'android.arch.lifecycle:extensions:1.1.1'
kapt 'android.arch.lifecycle:common-java8:1.1.1'

use these

implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
kapt 'androidx.lifecycle:lifecycle-common-java8:2.2.0'
Tegucigalpa answered 16/2, 2020 at 16:50 Comment(0)
T
1

If you're using Hilt Dependency Injection, You probably have missed @ViewModelInject. Because, Hilt provide its own injection for viewmodel.

In my case, I used and @Inject due to this caught into the error.

Transgression answered 10/3, 2021 at 18:4 Comment(1)
If you face this issue in Kotlin Dagger Hilt even after adding annotations HiltViewModel and Inject, make sure you have updated all hilt dependencies.Apochromatic
S
1

I had a different scenario when creating a view model instance:

  1. I was requesting for the instance in a fragment.
  2. My ViewModel required a parameter to be passed on the constructor.
  3. I was not using Dependency Injection.

Solution In a scenario where your viewmodel requires a parameter to be passed you have to create a ViewModelFactory to define your instances

Solution In Practice

- ViewModel Sample

    class SharedViewModel(private val repository: UserRepository) : ViewModel() {
    
     init {
            viewModelScope.launch {
                repository.refreshDataInDb()
            }
        }
    
    }
    
    

 - Creating ViewModel Factory

    
    class ViewModelFactory(
        private val repository: UserRepository
    ) : ViewModelProvider.NewInstanceFactory(){
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
    
         return SharedViewModel( repository as UserRepository) as T
          
        }
    }
    
    

 - Creating ViewModel Instannce in a Fragment

     private  lateinit var factory: ViewModelFactory
     private lateinit var searchViewModel: SharedViewModel
     private lateinit var repository: UserRepository
    

    repository = UserRepository()
    factory = ViewModelFactory(repository)
    searchViewModel = ViewModelProvider(requireActivity(), factory)[SharedViewModel::class.java]
Sauger answered 4/2, 2022 at 8:2 Comment(0)
U
0

My problem was that the IDE had added a "abstract" modifier to my ViewModel class.

Uela answered 3/2, 2020 at 18:52 Comment(0)
H
0

Make ViewModal class and constructure public

Handsomely answered 27/4, 2020 at 10:57 Comment(0)
P
0

If constructor of your viewmodel is public and accepts only application then make sure you can create your own model without ViewModelProvider. Error message might be much more clear:

val model = YouViewModel(app)
Photoreconnaissance answered 25/5, 2020 at 11:57 Comment(0)
A
0

I'm a proficient Android developer and I have used ViewModel 100s of times with no issue. Today I came across this issue. Spent hours and scrolled through various SO posts. Didn't get solved.

Then I saw that the package name in which I have the ViewModel contains new. Like this:

com.myapp.myfeature.new.feature

I changed new to neww for testing like this: com.myapp.myfeature.neww.feature

and it worked! I hope someone find it useful.

Andonis answered 3/12, 2020 at 12:2 Comment(3)
Good that it worked for you, however this has not got anything to do with ViewModels, you just can't use a keyword in the package name.Corinnacorinne
Yes Parag but there was no warning and error didn’t point to it. It was only random event to discover that the issue was with Package nameAndonis
You could have discovered this issue while working with anything else apart from ViewModels and just because you discovered this issue while implementing ViewModels doesn't make it a valid answer to the question asked above.Corinnacorinne
S
0

If you are using version 2.33-beta and upper remove these dependencies;

implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03"
kapt "androidx.hilt:hilt-compiler:1.0.0-beta01"

Keep only these two dependency

implementation "com.google.dagger:hilt-android:2.33-beta"
kapt "com.google.dagger:hilt-android-compiler:2.33-beta"
Saddlecloth answered 9/4, 2021 at 22:52 Comment(0)
O
0

In case you are using Jepack Compose with a ViewModel in your component. The @Preview annotation may cause this error. That was the problem in my case.

Olszewski answered 19/9, 2021 at 12:46 Comment(0)
M
0

Well this will fix the issue for sure

First of all make sure you have this dependency

//Room DB
implementation "androidx.room:room-runtime:2.2.5"
annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'

Then remove viewmodel constructor, then create init function as your constructor

 public void init(Application application){
        instance = new FirebaseDatabaseInstance();
        databaseRepository = new DatabaseRepository(application);
        allChatMembers = databaseRepository.getAllChatMembers();
    }

Then this will solve...

Mcfadden answered 25/4, 2022 at 9:25 Comment(0)
F
0

Not for OP's case, but adding it here for newcomers.

If you inherit from AndroidViewModel and there is some heavy work in the main Thread (like accessing the database) it'll wrongly throw this error.

After I switched to inherit from ViewModel, it showed the correct error and I could move the heavy work to Dispatchers.IO. After moving UI blocking stuff to Dispatchers.IO, I re-tested using AndroidViewModel and everything works fine again.

Conclusion: "UI blocking work on the main thread when inheriting from AndroidViewModel can throw this error".

Froemming answered 20/8, 2022 at 17:27 Comment(0)
S
0

none of the above was my problem. I did added @HiltViewModel and @AndroidEntryPoint and @HiltAndroidApplication like i had before and my code worked. the problem was that my project was multi-module and when i added the annotations it actually imported theme from other submodule but because the module didn't have those dependency in its own gradle.build it didn't compile, so i added these as same as other modules and it worked:

// Hilt
implementation("com.google.dagger:hilt-android:2.47")
kapt("com.google.dagger:hilt-compiler:2.44.2")
Serotherapy answered 10/9, 2023 at 12:17 Comment(0)
C
-2

I'm using this example android-arcuitecture-component BasicSample to make a new project, facing a similar error log, found I did'n change de applicatio name

AndroidManifest.xml

and that was my error, to fix put the aplicacion name to de BasicApp, this class is implement in the example.

...
<application
    android:name=".BasicApp"
    android:allowBackup="false"
Cispadane answered 19/5, 2019 at 18:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.