Я вызываю API на веб-сервер, и я возвращаю его обратно в метод onResponse.Возвращаемая переменная from onResponse Retrofit
Теперь я хочу сохранить этот идентификатор и вернуть этот идентификатор в возврате метода doLogin. Как я могу получить идентификатор переменной в операторе return?
Это мой код:
public class LoginController {
public static String doLogin(String loginMail, String loginPassword) {
//Logging Retrofit
final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("###URLTOAPICALL###")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<JsonElement> call = service.doLogin(loginMail, loginPassword);
call.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
if (response != null) {
JSONObject obj = null;
try {
obj = new JSONObject(response.body().toString());
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject setup = null;
try {
setup = obj.getJSONObject("setup");
} catch (JSONException e) {
e.printStackTrace();
}
if(setup != null) {
try {
Setup stp = new Setup();
stp.setUserId(setup.getInt("id"));
//I WANT HERE TO SAVE MY ID
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
Log.v("ERROR", t+"");
}
});
return "I WANT RETURN THAT ID HERE";
}
}
объявить 'int id;' и затем установить id 'id = setup.getInt (" id ");'. Теперь 'return id' в конце –
Короткий ответ: вы не можете .....' onResponse' - асинхронный обратный вызов –
Этот комментарий не помогает вообще. onResponse isync, но ответ isnt (если вы вызываете execute вместо enqueue). –