There is a certain set of string data ArrayList<String> strings , which we obtain by parsing some web page. Parsing naturally occurs in a separate thread, but when I try to output this data to a cardview or just a listview using an adapter, no data comes. The data will be displayed only if you forcefully ask the main thread to wait for the side thread to be executed. Like this:

 try { strings = stringsTask.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } 

How can you avoid such a design? I assume that you need to onPostExecute() something in the onPostExecute() task, but I do not know what. The specified MainActivity.adapter.notifyDataSetChanged(); does not work (i.e., after all data is fully loaded, the data is still not updated). I tried to clearly explain my problem, but if I failed, please write about it.

    1 answer 1

    1. Do not make the adapter a static field of activation.
    2. In onPostExecute you receive your data as an argument. It is in this method that you need to create an adapter with them,
    3. Assign it to a ListView or RecyclerView or something else.
    4. Now you can call notifyDataSetChanged() on the adapter.
    • But what about the context that needs to be used in the adapter? and assign it to RecyclerView will it be possible, without declaring it recyclerView as static? Otherwise, you will need to create it in the same onPostExecute , but you will create it and you will not be able to find it, since findViewById cannot use findViewById there. - whalemare
    • one
      @whalemare, just pass context and Recycler to the AsyncTask as constructor arguments and assign them to the class fields. So in onPostExecute you can create an adapter, assign it, and use a context. - YurySPb
    • too .. For some reason I decided that in AsyncTask you can transfer data only through nameAsync.execute(data) , without remembering about the designer .. Thank you very much for your help!) - whalemare
    • @whalemare, please) - Yuriy SPb