Это происходит потому, что вы не инициализируете экземпляр ApiInterface
.Вам необходимо создать свой ApiInterface
с помощью Retrofit:
public ApiInterface createApi() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(your_api_url)
.addConverterFactory(GsonConverterFactory.create(new Gson())) // for automatic serialization using Gson
.build();
return retrofit.create(ApiInterface.class);
}
. Вы можете определить его в хранилище:
public class CurrencyRepository {
private ApiInterface apiInterface;
public CurrencyRepository(Application application) {
apiInterface = createApi();
}
public LiveData<Currency> getCurrency(String base, String target) {
final MutableLiveData<Currency> data = new MutableLiveData<>();
apiInterface.getCurrentCurrency(base, target).enqueue(new Callback<Currency>() {
@Override
public void onResponse(Call<Currency> call, Response<Currency> response) {
data.setValue(response.body());
}
@Override
public void onFailure(Call<Currency> call, Throwable t) {
}
});
return data;
}
}
или пройти через конструктор:
public CurrencyRepository(ApiInterface apiInterface) {
this.apiInterface = apiInterface;
}
// then
public MainViewModel(Application application) {
super(application);
currencyRepository = new CurrencyRepository(createApi());
}
Или передайте ApiInterface
через конструктор, используя DI Framework (Dagger2 или Toothpick).