devcodes
devcodes

Reputation: 1088

Getting data from AsyncTask class to the Activity

I am trying to retrieve data from the AsyncTask class's onPostExecute() and set it as the text for textviews of the same activity (so just to test i am using toast to see if it works).

I am using an interface (with method processFinish()) as follows to get data from onPostExecute().

But the data is not available to the Outer Activity class : -

interface AsyncResponse{
  void processFinish(String[][] output);
    }

MainActivity -

 public class VPmovies extends Activity implements AsyncResponse  {
  MyAsyncClass myAsyncClass  = new MyAsyncClass();
  String[][] mov_details;

   protected void onCreate(Bundle savedInstanceState) {
      myAsyncClass.asyncResponse=this;
      myAsyncClass.execute();
      mov_details=new String[6][9];

    super.onCreate(savedInstanceState);
    setContentView(R.layout.vpmovies);

   Toast.makeText(this,"onCreate"+mov_details[0][1],Toast.LENGTH_LONG).show();


  // output from here is - "onCreate**null**"
   }

  public void processFinish(String[][] output) {

               mov_details = output;

    }

MyAsyncClass's onPostExecute() -

 protected void onPostExecute(String[][] strings) {
      //  super.onPostExecute(strings);
         asyncResponse.processFinish(strings);
        Toast.makeText(VPmovies.this,"onPostToast"+strings[1][0],Toast.LENGTH_LONG).show();
        //THIS prints the data from the array successfully
    }

Is the AsyncTask Class still performing its operation in background while onCreate() is executed ? Is that why i am getting null for the array element ? Is there a way to delay onCreate() to be executed after AsyncTask completes its operation ?

Upvotes: 1

Views: 863

Answers (1)

Abhijeet Gupta
Abhijeet Gupta

Reputation: 124

You can use the get() method of AsyncTask class for adding delay in execution of onCreate().Such as -

myAsyncClass.execute().get();

Upvotes: 4

Related Questions