Search code examples
androidandroid-asynctaskadapterlistadapter

Setting ListAdapter after Task completes


In my code I do something like this

// Start AsyncTask - And load Network data into an Object
// Set ListAdapter with Object from Task.

However, The Task never completes before the ListAdapter tries to be set, so it is null.

Setting the adapter in the onPostExecute is not an option because this Task is its own class and is used in other areas.

I think the main problem here is the Async part of Task. Is there a better way to be doing this?


Solution

  • Converting comments to answer

    You can create a constructor in your AsyncTask that will take whatever params you need from this Activity for instance a Context and a ListAdapter or boolean as you chose. Then when you create an instance of the AsyncTask you can pass in these params

    MyTask myTask = new MyTask(MainActivity.this, booleanVar);  // passing Context and boolean
    myTask.execute();
    

    Then in your AsyncTask you can check if a certain variable is null or check for boolean value to decide what to do in onPostExecute()

    Then you can have a constructor that deals with a different set of params for the other Activities that need to use it