Retrofit2 ApiInterface.getCurrentCurrency (java.lang.String, java.lang.String) 'для ссылки на пустой объект - PullRequest
0 голосов
/ 28 декабря 2018

Я пытаюсь изучить Retrofit2 с архитектурой MVVM, и у меня есть проблемы с нулем:

retrofit2.Call com.example.daniellachacz.currencyconverter2.data.network.ApiInterface.getCurrentCurrency (java.lang).String, java.lang.String) 'для пустой ссылки на объект

ApiInterface

public interface ApiInterface {

@GET("currency")
Call<Currency> getCurrentCurrency(@Query("base") String base,
                                  @Query("target") String target);
}

CurrencyRepository.class

public class CurrencyRepository {

private ApiInterface apiInterface;

public CurrencyRepository(Application application) {

}

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;
}

}

MainViewModel.class

public class MainViewModel extends AndroidViewModel {

private CurrencyRepository currencyRepository;
public final ObservableField<String> base = new ObservableField<>();

public MainViewModel(Application application) {
   super(application);
   currencyRepository = new CurrencyRepository(application);
}

public void setBase() {
    String mBase = "EUR";
    String mTarget = "PLN";
    currencyRepository.getCurrency(mBase, mTarget);
    base.set(mBase);
}
}

1 Ответ

0 голосов
/ 28 декабря 2018

Это происходит потому, что вы не инициализируете экземпляр 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).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...