D
D
davidnum952016-03-27 20:12:01
Java
davidnum95, 2016-03-27 20:12:01

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) {

            }
        });

    }
}

Calling the Authenicate method:
public void onClick(View view) {
        loginData = new LoginData(inputPhone.getText().toString(), inputPassword.getText().toString());
        Authentication.Authenticate(loginData);
        switch (Authentication.responseCode) {...}

ApiService class code:
public interface ApiService {
    @Headers( "Content-Type: application/json" )
    @POST("users/login")
    Call<String> getAccessToken(@Body LoginData loginData);

}

LoginData Model:
@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

2 answer(s)
D
Denis Zagaevsky, 2016-03-27
@davidnum95

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.

B
belozerow, 2016-03-27
@belozerow

Don't do this:

public static String accessToken;
public static int responseCode;

responseCode not yet initialized here
Check if it hits
@Override
            public void onFailure(Call<String> call, Throwable t) {

and if so, then by mistake in t you will understand for yourself what the problem is

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question