Help! Why is the onComplete method running synchronously, not asynchronously?

findViewById(R.id.button8).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final ProgressDialog pd = new ProgressDialog(MainActivity.this); final Handler h = new Handler() { public void handleMessage(Message msg) { pd.setMessage("Загрузка..."+msg.what); if(msg.what==20) pd.dismiss(); } }; Thread t = new Thread(new Runnable() { public void run() { for(int i =0; i<=10; i++){ try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) {} h.sendEmptyMessage(i); } VKRequest request = VKApi.wall().get( VKParameters .from("domain", "serd_donbassa", "count", "200", "offset", "0")); request.executeWithListener(new VKRequestListener() { public void onComplete(VKResponse response) { for(int i =10; i<=20; i++){ try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) {} h.sendEmptyMessage(i); } } }); } }); pd.setMessage("Загрузка..."); pd.setCancelable(false); pd.show(); t.start(); } }); 

This code updates only up to 10, and then hangs for 10 seconds (the ProgressDialog stops spinning), and then disappears. It follows from the above that the method runs asynchronously. How to fix it?

  • Why such complexity? may try asyncTask. easier and clearer there too - Saidolim
  • @Saidolim, tried: the onComplete method is not implemented at all - Vlad Glushko

2 answers 2

The onComplete method from VKSDK always executed in the main (UI) application thread. So it is done. If at this moment you need to perform another asynchronous operation, then start it in a new thread in the same way as you already do or through AsyncTask .

  • Maybe this behavior can be fixed here by this setUseLooperForCallListener(boolean useLooperForCallListener) in the VKRequest class. But he didn’t comment and I didn’t quite understand what he was doing. - Yuriy SPb

Instead of executeWithListener , use executeSyncWithListener