3

I'm trying to use the value initialized on onPostExecute(...) in other methods, but when I call the value from another method, or another class, the value is returned as null. Presumably because the function grabs the value BEFORE it finishes loading. I tried using a do-while using boolean checks to wait for the value to finish loading (ex. do(initialize) while(!isDoneLoading)), but I get an infinite loop. The only things I have found online have said to use the postExecute to update UI components, but I need that value to grab more information from url responses!

public class StaticData{
    private String mMostRecentVersion;

    private void setMostRecentVersions(URL url){
        ...
        ...
        ...
        new AsyncTask<URL, Void, JSONArray>() {
            @Override
            protected JSONArray doInBackground(URL... params) {
                return loadJSON(params[0]);
            }

            @Override
            protected void onPostExecute(JSONArray array){
                try {
                    mMostRecentVersion = array.get(0).toString();//THIS IS THE VALUE I WANT
                    Log.d("MyApp", "Recent Version: " + mMostRecentVersion);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.execute(url);
    }
}

The Log.d on the onPostExecute method returns the value I need in its correct form. The issue is that calling this value from other methods returns null.

Oscar A Garcia
  • 173
  • 5
  • 18

1 Answers1

1

Since the doInBackground method runs on different thread it may take some time to execute and assign value to your global variable. May be you are accessing the value of global variable in another method before completing the asynctask. You can check it by assigning some value to global variable initially. And it will be printed. So you can use the variable only after completing the asynctask.

Update

You have to set a Boolean in onPostExecute to notify the asynctask has finished.. Ex:

        onPostExecute(){
            isCompleted = true 
            ....
            ...
            ...             
        }

    public void anotherMethod(){
       while(isCompleted){
        //operations
       }
   }

Or you can use interface call back

droidev
  • 7,352
  • 11
  • 62
  • 94