Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing strings.xml from ViewModel

I am using Dagger 2 DataBindng and the new Android Lifecycle components, which have ViewModels.

Inside my ViewModel how could I get access to my strings.xml? I was thinking at first, to inject a Context into the viewModel, however, this will just leak memory.

Are there any other ways?

like image 244
Robert J. Clegg Avatar asked Sep 27 '17 08:09

Robert J. Clegg


People also ask

How do I access resources from ViewModel?

Just create a ResourceProvider class that fetch resources using Application context. In your ViewModelFactory instantiate the resource provider using App context. You're Viewmodel is Context free and can be easily testable by mocking the ResourceProvider.

Where is strings XML in Android Studio?

XML file saved at res/values/strings.

What is difference between AndroidViewModel and ViewModel?

The AndroidViewModel extends ViewModel , so it has all the same functionality. The only added functionality for AndroidViewModel is that it is context aware: when initializing AndroidViewModel you have to pass the Application context as a parameter.

Can we get context in ViewModel?

Can we use context in ViewModel Android? 1. No Android Framework references in ViewModel. It is a good practice (but not mandatory) to keep ViewModel free from Android framework references like Activity, Context, Drawables etc.


1 Answers

There is an AndroidViewModel, which receives Application instance as parameter.

From docs:

Application context aware ViewModel.

Subclasses must have a constructor which accepts Application as the only parameter.

You can retrieve a string from strings.xml using that parameter.


The repo in the link, however uses ViewModel and not AndroidViewModel. If I extend my ViewModel to use AndroidViewModel and include the Application - it's trying to inject MyApplication instead of Application if that makes sense.

I've checked out GithubBrowserSample. Here's how UserViewModel looks like:


    public class UserViewModel extends ViewModel {
        ...
        @Inject
        public UserViewModel(UserRepository userRepository, RepoRepository repoRepository) {
            ...
        }
        ...
    }

And here's what changes I've done:


    public class UserViewModel extends AndroidViewModel {
        ...
        @Inject
        public UserViewModel(Application application, UserRepository userRepository, RepoRepository repoRepository) {
            super(application);
            ...
        }
        ...
    }

like image 67
azizbekian Avatar answered Sep 22 '22 13:09

azizbekian