The application should periodically load JSON from the server. To load JSON, to process it is not a problem. Can not loop.
For example, in activit tried to do this:

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_master_view); ListView listView = (ListView)findViewById(R.id.list); Downloader downloader = new Downloader(this); SimpleAdapter adapter; while (true){ downloader.execute(); try { listOfElements = downloader.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } adapter = new SimpleAdapter( this, listOfElements, R.layout.list, new String[]{ TITLE, TEXT,}, new int[]{ R.id.title, R.id.text} ); listView.setAdapter(adapter); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); try { TimeUnit.MILLISECONDS.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 

Error IllegalStateExeption takes off: Cannot execute task: the task is already running. I tried to use Thread.sleep () instead of TimeUnit - it also crashes. Where is the mistake?

    1 answer 1

    1. It is necessary to recreate each time AsyncTask (of type new Downloader() ) - this is a more accurate way than to restart it through the execute
    2. It is necessary to track the completion of a task through AsyncTask.onPostExecute() setting a listener or at least a synchronized boolean flag and launch a new task only after the previous one is finished - creating the task again (see item 1)
    • And why is it better to create a new AsyncTask? - Stas0n
    • one
      AsyncTask is not better to re-create, but to re-create. - KoVadim
    • And how do I catch the moments when, let's say I need to do the load without waiting for a certain period of time to expire, and when the application clicked on the "reload" button? Those. How to make the timer go, but there was an opportunity to catch a button press? - Stas0n
    • And why make some kind of explicit construction to track the end of loading in AsyncTask, if there is a get () method that just waits for the main thread to get something from AsyncTask. While waiting, in theory, TimeUnit.MILLISECONDS.sleep (2000); should not work - Stas0n
    • [Stas0n] [1], with such an implementation, the "reload" button does not make sense - because at the moment of clicking the application will either wait or sleep, or throw away [ANR] [2] even before the user sees something [ 1]: hashcode.ru/users/9148/stas0n [2]: developer.android.com/training/articles/perf-anr.html - woesss