0

I have a Inner class which extends AsyncTask inside my main class

public class MainActivity extends Activity {
String variable;
public onCreate(){

    onClickListener{
    new InnerClass().execute(params);
    variable // Here the value is always null
    }
}

class InnerClass extends AsyncTask<String,Void,JSONObject>{
    protected JSONObject doInBackground(String... params){
        /* Relevant Code 
        */
    }

    protected void onPostExecute(JSONObject result){
    variable = value; // required value being assigned to the variable
    }

}
}

I am getting proper value assigned to the my String Variable "variable" in the inner class, but i am not able to the access the value in my main class.

Tim
  • 41,901
  • 18
  • 127
  • 145
StrawhatLuffy
  • 695
  • 1
  • 7
  • 17
  • You shouldn't expose around public variables like that. Instead use a callback and use that in the inner class to trigger a method in the main class – Tim Sep 22 '15 at 09:26
  • That's because you're looking at the value before the async task has set it... – user253751 Sep 22 '15 at 09:26

4 Answers4

2
new InnerClass().execute(params);
variable // Here the value is always null

You call execute but your main thread continue, so variable is still null because AsyncTask.onPostExecute was still not called.

David Herrero
  • 704
  • 5
  • 17
0

You use async task, it creates thread for you to execute your code. Your variable is null because your thread didn't finish his job.

Artur Szymański
  • 1,639
  • 1
  • 19
  • 22
0

create inner class object like.

InnerClass inner=new InnerClass();
String name=inner.name;

That's it.

Ganpat Kaliya
  • 888
  • 2
  • 9
  • 16
0

If you wan result from your asynk task you can do like that: Separate class for asynk task:

class InnerClass extends AsyncTask<String,Void,JSONObject>{
  protected JSONObject doInBackground(String... params){
    /* Relevant Code 
    */
  }
}

In your activity:

public class MainActivity extends Activity {
  String variable;
  public onCreate(){

     onClickListener{
      startAsync();
     }
   }
  private void startAsync(){
         InnerClass task = new InnerClass(){

          protected void onPostExecute(JSONObject result){
              variable = value;
          }

         };
         task.execute(params);

  }
 }

This is only for adaptation of your code. Better way is to make long tasks in appliaction context ,and sending results to activities/ fragments by EventBus. If you use above implementaion you have to create methods to canceling task when onDestroy is called.

Adam Miśtal
  • 715
  • 4
  • 15