Большинство библиотек квадрата имеют довольно хорошие примеры на страницах своих проектов, вы должны ссылаться на них перед обучением при использовании библиотек.
аюсь обновить этоРетрофит + Отто учебниктак что мой код обновлен:
IWeather.java
RetroFit 2. + не позволяет вернутьсяvoid
так что вместоvoid getWeather(...)
я добавилCall<Weather> getWeather(...)
.
public interface IWeather {
@GET("/{latitude},{longitude}")
Call<Weather> getWeather(@Path("latitude") String latitude,
@Path("longitude") String longitude,
Callback<Weather> callback);
}
ForecastClient.java
RetroFit 2. + изменил свой конструктор, поэтому новыйForecastClient
имеет следующую форму.IllegalArgumentException
указывает наweather.getWeather(...)
метод.
public class ForecastClient {
private static final String BASE_URL = "https://api.darksky.net/forecast/";
private static final String API_KEY = "******************";
public static final String API_URL = BASE_URL + API_KEY + "/";
private static ForecastClient mForecastClient;
private static Retrofit mRetroAdapter;
public static ForecastClient getClient() {
if (mForecastClient == null) {
mForecastClient = new ForecastClient();
}
return mForecastClient;
}
private ForecastClient() {
mRetroAdapter = new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(new OkHttpClient())
.build();
}
public void getWeather(String latitude, String longitude, Callback<Weather> callback) {
IWeather weather = mRetroAdapter.create(IWeather.class);
weather.getWeather(latitude, longitude, callback);
}
}
ForecastManager.java
public class ForecastManager {
private Context mContext;
private Bus mBus;
private ForecastClient sForecastClient;
public ForecastManager(Context context, Bus bus) {
this.mContext = context;
this.mBus = bus;
sForecastClient = ForecastClient.getClient();
}
@Subscribe
public void onGetWeatherEvent(GetWeatherEvent getWeatherEvent) {
String latitude = Double.toString(getWeatherEvent.getLatitude()).trim();
String longitude = Double.toString(getWeatherEvent.getLongitude()).trim();
Callback<Weather> callback = new Callback<Weather>() {
@Override
public void onResponse(Call<Weather> call, Response<Weather> response) {
Log.d(ForecastManager.class.getSimpleName(), response.body().toString());
mBus.post(new SendWeatherEvent(response.body()));
}
@Override
public void onFailure(Call<Weather> call, Throwable t) {
Log.e(ForecastManager.class.getSimpleName(), t.getMessage());
}
};
sForecastClient.getWeather(latitude, longitude, callback);
}
}
Я получаю аннотацию No Retrofit, найденную, и я предполагаю, что причина связана с моим обратным вызовом, но это обратный вызов RetroFit, поэтому я не понимаю, почему произошла ошибка.
Трассировка стека указывает на MainActivity, в частности на метод Оттоpost()
сjava.lang.RuntimeException: Could not dispatch event
, вызванный ранее упомянутой ошибкойjava.lang.IllegalArgumentException: No Retrofit annotation found. (parameter #3)
:
MainActivity.java
public class MainActivity extends AppCompatActivity {
@BindView(R.id.activity_main_textView)
TextView textView;
@BindView(R.id.activity_main_button)
Button button;
private static final double LATITUDE = **.******;
private static final double LONGITUDE = **.******;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@OnClick(R.id.activity_main_button)
public void onClick(View view) {
BusProvider.getInstace().post(new GetWeatherEvent(LATITUDE, LONGITUDE));
}
@Subscribe
public void onSendWeatherEvent(SendWeatherEvent sendWeatherEvent) {
Weather weather = sendWeatherEvent.getWeather();
Currently currently = weather.getCurrently();
textView.setText(currently.getSummary());
}
Любая подсказка о том, где ошибка или как я должен обрабатывать автобусные подписки, обратный вызов, и так далее?