I was using fragment and now I attached ViewModel to it and was transferring code to ViewModel and activity?.packageManager?.getPackageInfo(uri, PackageManager.GET_ACTIVITIES)
this line shows an error. How can I access package manager in ViewModel?
Question posted in Android Studio
The official documentation can be found here.
The official documentation can be found here.
2
Answers
On way is to extend
AndroidViewModel
instead ofViewModel
as:Now you can call:
Theoretically if you are implementing MVVM pattern (I see you implementing ViewModel), android.* layer should be handled in the View, Activities/Contexts shouldn’t be managed in the ViewModel to avoid Memory Leaks. Even though, depending on the project context, of course this rule doesn’t apply to every single project context, I think the best approach would be (if not Dependency Injection is been used) to have an Application Provider.
Create an object:
In your MainActivity, initialise the ApplicationProvider as the following:
Now you can access the ApplicationContext in your whole project where is needed with:
Remember to not assign ApplicationContext to static fields (as a val e.g.) to avoid Memory Leaks.
PD: I’m not very fan of AndroidViewModel, but I guess it is a good solution as well, as a colleague mentioned before 😀