2

For example, I have the following class:

public class MyClass{

  private static int x;
  private AsyncWorker worker;


  public void myVoid(){
     worker = new Worker;
     worker.execute();
     if (x == null){
         Log.v("Say something: ", "x is null");
     }
  }


class AsyncWorker extends AsyncTask<Void, Void, Void>{

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub

            x = 10;

            return null;
        }

        @Override
        protected void onPostExecute(Void result){
            super.onPostExecute(result);

        }
}

}

At the result, it prints that x is null. Is there any way to change x from AsyncTask and use it's value in future?

1
  • 1
    This is probably because you are now using another thread that works independently from the main thread. So the x == null check will execute immediately after task.execute() Commented Jan 8, 2013 at 16:12

1 Answer 1

3

You need to read up on threading and the user of ASyncTask. When you call execute on your AsyncTask, myVoid goes straight on to the next line as ASyncTask is running on a different thread, so x will always be null as the AsyncTask won't have done anything yet. You're also introducing problems here with crossthreading and variable synchronisation.

In the nicest way possible, I would recommend that you take the question down and find a decent tutorial on the use of AsyncTask and threads

Sign up to request clarification or add additional context in comments.

2 Comments

I've been programming Android for a while, and I actually found this question helpful. I've read a lot of AsyncTask tutorials, and not many at all deal with the issue of accessing external variables. Please keep it around! :-)
@David except that any tutorial on threads will explain what the OP was doing wrong when it comes to accessing an external variable from a separate thread, but checking it for the change immediately in the original thread. As for passing a result back from an AsyncTask, the best way is to create a result listener and send the variable back that way. You can pass variables into an AsyncTask using the constructor of the class, which is especially important when the AsyncTask gets bigger, as then you don't want it as an internal private class, but a separate class, then can't access it like above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.