0

I want to get something from SharedPreferences in a ViewModel class. The constructor has a SavedStateHandle parameter only and I don't know how to get the context. Here is my code:

public class PropertyDetailActivityViewModel extends ViewModel{

    public enum Event{
        Ok, Ko
    }

    public MutableLiveData<Event> event = new MutableLiveData<>();

    public MutableLiveData<Property> property = new MutableLiveData<>();

    private final Property propertyExtra;


    public PropertyDetailActivityViewModel(SavedStateHandle savedStateHandle) {
        propertyExtra = savedStateHandle.get(PropertyDetailActivity.PROPERTY_EXTRA);
        property.postValue(propertyExtra);
    }

    public void deleteProperty()
    {
        if(AppPreferences.getAgentName(//How to get context here?) == propertyExtra.agent)
        {

        }
    }
}

viewModel definition in the view class:

viewModel = new ViewModelProvider(this, new SavedStateViewModelFactory(getApplication(), this, getIntent().getExtras())).get(PropertyDetailActivityViewModel.class);
Pierre A
  • 15
  • 4
  • Why not use `AndroidViewModel`, then create a custom `SavedStateViewModelFactory` to init it? Here's more info. on the later part: https://stackoverflow.com/questions/62850680/savedstateviewmodelfactory-is-finall-cannot-inherit – Darshan Dec 12 '20 at 13:05
  • Thanks for your answer. I'm just a beginner in Java Android so I did not really get what you said or the answer on your link. Can you give me more details please? – Pierre A Dec 12 '20 at 13:59
  • Check the docs. for `AndroidViewModel` which gives you access to a `applicationContext` – Darshan Dec 12 '20 at 14:03
  • Oh thanks, it was that simple...I just needed to replace ViewModel by AndroidViewModel and add an Application parameter to my constructor – Pierre A Dec 12 '20 at 14:10

0 Answers0