I figured this must be a common question, but I surprisingly couldn’t find an answer, so maybe my entire structure is terribad…
I have an activity which downloads values/states of a game from a web service via AsyncTask. These values are used to update a custom view.
Once the view is created, various events from the view launch an AsyncTask to download other information.
This is functional, but the problem is I now have half a dozen AsyncTask classes in the activity with almost identical code. The only difference is the type of object that is returned (which is based on the json from the web service) and the method that is called from onPostExecute().
How can I use just two AsyncTask (one for post and one for get) without knowing what type of json object will be returned by the web service?
In a similar vein, how can I determine the type of object returned by the web service? The web service, if there is a problem, will return a json string that correlates to an ErrorMessage object rather than (for example) a GameData object.
Should I be using switch and instanceof in onPostExecute() somehow? Callbacks maybe?
You can use an abstract base class, which your related classes extends.
Sample code:
and for example, use it like this:
This is just from the top of my head. I couldn’t relate to your specific problem, although the ideas here should be enough to get you started on your new structure.