Answer the question
In order to leave comments, you need to log in
Why is the code in the callback not being executed?
Good afternoon. I can't figure out why the code in the onResponse() method is not being executed.
public class Authentication {
public static String accessToken;
public static int responseCode;
//Get access token and create db with user profile and orders
public static void Authenticate(LoginData loginData) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://какойтосайт.ru/api/v1/")
.addConverterFactory(JacksonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
Call<String> call = apiService.getAccessToken(loginData);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
//Код ниже почему то не выполняется
responseCode = response.code();
accessToken = response.body().substring(18, 49);
}
@Override
public void onFailure(Call<String> call, Throwable t) {
}
});
}
}
public void onClick(View view) {
loginData = new LoginData(inputPhone.getText().toString(), inputPassword.getText().toString());
Authentication.Authenticate(loginData);
switch (Authentication.responseCode) {...}
public interface ApiService {
@Headers( "Content-Type: application/json" )
@POST("users/login")
Call<String> getAccessToken(@Body LoginData loginData);
}
@JsonPropertyOrder({"phone", "password"})
public class LoginData {
@JsonProperty("phone")
public String Phone;
@JsonProperty("password")
public String Password;
public LoginData(String phone, String password) {
this.Phone = phone;
this.Password = password;
}
}
Answer the question
In order to leave comments, you need to log in
The code is executed there, you just didn't wait for it. The bottom line is that call.enqueue executes the request asynchronously, on a different thread. And you have switch in MainThread. When it comes to switch(Authentication.responseCode), the request has not yet completed. You need to call this logic from within the callback.
Don't do this:
public static String accessToken;
public static int responseCode;
@Override
public void onFailure(Call<String> call, Throwable t) {
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question