How to make the program expect to execute call_summoner_id?

public void get_summoner_id(String REGION, final String summoner_name) { final Request request = new Request.Builder().url(this.GETURL.get_url_summoner_by_summoner_name(summoner_name, REGION)).build(); GETCALL.call_summoner_id(request); set_summoner_id(GETCALL.summoner_id); } public void call_summoner_id(Request request){ client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); listener.onFailure(); } @Override public void onResponse(Call call, Response response) throws IOException { try { Response response_summoner = response; System.out.print(response_summoner); JSONObject json = new JSONObject(response.body().string()); final String new_summoner_id = json.getString("id"); summoner_id = new_summoner_id; } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }); } 

2 answers 2

Head-on:

 int beforeRequest = GETCALL.summoner_id; GETCALL.call_summoner_id(request); int afterRequest = GETCALL.summoner_id; while(beforeRequest == afterRequest){ //Thread.sleep(500); afterRequest = GETCALL.summoner_id; } set_summoner_id(GETCALL.summoner_id); 

You have posted little information, but from the fact that there is, perhaps you should create an observer who, when you change GETCALL.summoner_id will do the work you need.

Observer (design pattern)

    This is possible only if you perform all actions in one thread. In the case of an android, it should not be the main thread. You, apparently, need to assign a certain ID in the main thread, while getting the ID from the result of the network query. In this case, you cannot do it in one thread, because requests to the network from the main stream are directly prohibited.

    You need to completely change the logic. It is necessary to proceed from the fact that a network request may take an unknown time (sometimes several minutes) and often simply ends with an error. Those. you need to run the query and forget about it. Further, in callbacks of its completion, handle successful / unsuccessful completion.

    A simple synchronous approach in the case of working with data from to-l sources (network / database) will not work out in any way.