0

I am learning MVVM and trying to get context in my repository and pass a value from the MainActivity to the repository class.

I know you can get context in the ViewModel through Application:

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

        ...
    }

myApi = RetrofitService.getClient(getApplication()).create(ApiInterface.class);

But how does it work for a repository class and how can I pass a String value (utc) from MainActivity to the repository class?

I have following example code for my repository class:

private String utc:

public RetroDataRepository() {

public MutableLiveData<TimezoneModel> getTimeZones() {

        final MutableLiveData<TimezoneModel> timezones = new MutableLiveData<>();
        apiInterface = RetrofitService.getClient(context????).create(ApiInterface.class);
        Call<ResponseBody> call = apiInterface.getTimeZone(utc);
        call.enqueue(new Callback<ResponseBody>() {

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                String time;
                String utc;
                String region;
                String currentTime;
                String timezoneTitle;

                if(response.body()!=null) {
                    // store TimeZone data to a list
                    Document document = Jsoup.parse(response.body().toString());

                    ....
                }

                isLoading.setValue(false);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

                Log.e(TAG, "onFailure: ", t);
                isLoading.setValue(false);
                error.setValue(true);
            }
        });

        return timezones;
Simon
  • 1,691
  • 2
  • 13
  • 28
  • Call your repository method from your ViewModel. Pass your string as a method parameter. Never use contexts in your repository classes. – p.mathew13 Jun 10 '19 at 12:42
  • https://stackoverflow.com/questions/2002288/static-way-to-get-context-in-android?answertab=votes – Mini Chip Jun 10 '19 at 12:46

0 Answers0