You only need to run a task after an asynchronous task completes
How to make sure that asynchronous tasks complete before I run some tasks. I need to use a variable after the asynchronous task changes the value of that variable. If I run the code before the asynchronous run completes, then I’m screwed. Does it help? I’m obviously new to asynchronous tasks. If you look at my code, I may not be using onPostExecute() as expected, so suggestions would help. My initial idea was to keep adding things to async tasks, but I thought it was just a bad practice because I had a lot of stuff that had to run continuously. Basically, I think it comes down to: how do I make sure that tasks in the UI thread don’t start running before my async tasks complete.
public class MainActivity extends MapActivity {
myJSONmap;
public void onCreate(Bundle savedInstanceState) {
new AsyncStuff().execute();
locatePlace(myJSONmap);
class AsyncStuff extends AsyncTask<Void, Integer, JSONObject> {
@Override
protected JSONObject doInBackground(Void... params) {
jObject = GooglePlacesStuff.getTheJSON(formatedURL);
return null;
}
@Override
protected void onPostExecute(JSONObject result) {
TODO Auto-generated method stub
super.onPostExecute(result);
myJSONmap = JSONextractor.getJSONHMArrayL(jObject); getting the parsed data from the JSON object.
the arraylist contains a hashmap of all the relevant data from the google website.
}
}
Solution
You may want to read more about AsyncTask for Android developers
http://developer.android.com/intl/es/reference/android/os/AsyncTask.html
Regarding tips, my personal choice is to pass a Boolean to onPostExecute. This allows you to evaluate whether doInBackground was successful and then determine what to do (error messages or update the layout).
Keep in mind that in the onPostExecute method, ideally only screen updates should occur, assuming your data is fine. In your example, why not include
myJSONmap = JSONextractor.getJSONHMArrayL(jObject);
On doInBackground? Then call
locatePlace(myJSONmap);
Like this:
class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {
String errorMsg;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Integer doInBackground(Void... v) {
try{
jObject = GooglePlacesStuff.getTheJSON(formatedURL);
myJSONmap = JSONextractor.getJSONHMArrayL(jObject);
do stuff
return true;
} catch (JSONException e){
errorMsg="Something wrong in the json";
return false;
}
}
@Override
protected void onPostExecute(Boolean success) {
if(success){
locatePlace(myJSONmap);
update layout
} else {
show error
}
}
}