In general, the problem is this: I am writing a program to process information about the subscribers of the group using the VK API . In the doInBackground method doInBackground I try to get the number of required requests to process all users ( VK API can return a maximum of 1000 users at a time). To do this, I create a separate method and call a request in it, to which the listener hangs, and when I get the result, I calculate the necessary number of requests:

  //В зависимости от числа подписчиков выбирается нужное количество //запросов к серверу для того, чтобы обработать всех подписчиков private void getRequestCount() { final VKRequest request = VKApi.groups().getMembers(VKParameters.from( VKApiConst.GROUP_ID, groupId, //id группы, у которой получаю подписчиков VKApiConst.COUNT, 0)); //Пока что мне не нужна информация о подписчиках //Посылаю запрос и вешаю слушатель request.executeWithListener(new VKRequest.VKRequestListener() { @Override public void onComplete(VKResponse response) { String jsonString = response.responseString; int countSubscribers = 0; try { //Получаю количество подписчиков JSONObject jsonRootObject = new JSONObject(jsonString); JSONObject jsonObject = jsonRootObject.getJSONObject("response"); countSubscribers = jsonObject.getInt("count"); } catch(Exception e) { Log.e(TAG, "Error when parsing JSON: " + e.getMessage()); } //Узнаю количество нужных запросов к серверу, //один запрос возвращает макс. 1000 подписчиков int requests = countSubscribers/1000; //Деление нацело вернет только целое число от деления, дробная часть — //оставшиеся подписчики, их забираю дополнительным запросом if (count % 1000 > 0) requests++; requestCount = requests; } @Override public void onError(VKError error) { Log.e(TAG, "Error when requesting: " + error.errorMessage); } }); } 

And here is the doInBackground method:

 @Override public Object loadInBackground() { getRequestCount(); ... ... ... return writedSubscriber; } 

The problem is that the listener receives a response after the method completes, that is, the code in the doInBackground continues to execute without receiving a response. How can you "slow down" the method before receiving a response from the listener, and only then continue with the execution?

    1 answer 1

    You need to continue the logic inside the onComplete method, and not outside, in loadInBackground . So you execute the necessary code only after obtaining the necessary data.

    Those. transfer all code after calling getRequestCount in onComplete

    • I'm afraid that this option is not suitable. Then there will be another bunch of code and another bunch of similar requests. Here it is worth trying to get a link to SyncTask and slow it down through the methods (while sleeping, invented :)) .. - user189127
    • Intentionally slowing down the flow is a bad idea. If you don’t like the code, then just break it into separate methods - YuriiSPb
    • Yes, there is a bit of a problem here ... After receiving the required requests, in case an error pops up, I simply finish loading with the return "Error on request" method return "Error on request" , if not, I start receiving the same number of times with the same request method, respond and process file with suitable data (unfortunately, the algorithm will be confusing, but in this case the main thing is that it works). That is, here your option does not work well, but put threads on pause and so on. - quite an acceptable option. - user189127
    • Damn, AsyncTask can not be paused ... - user189127
    • one
      Well ... My inner perfectionist is in pain, but, once it works, let it be) - Yuriy SPb