9

Ok so now I have Class A that contains some spinners that values will be populated by Class B that extends AsnycTask which grabs the spinner values from a web service. In class B i manage to retrieve the values, showing in a Toast. The problem now is how do I pass those spinner values back to Class A?

I've tried

Can OnPostExcecute method in AsyncTask RETURN values?

by passing Class A to Class B and store the value in a public variable of Class A like below

@Override
protected void onPostExecute(String result)
{
  classA.classAvariable = result;
}

However whenever I try to read the classAvariable i always get a NullPointer Exception. Seems like the variable was never assigned with the result. For readability purpose I needed to seperate Class B instead of using as an inline class.

Any ideas my fellow Java programmers?

Community
  • 1
  • 1
Jack-V
  • 149
  • 1
  • 2
  • 8

3 Answers3

1

Problem here is that when you execute your AsynchTask, its doInBackground() methode run in separate thread and the thread that have started this AsynchTask move forward, Thereby changes occur on your variable by AsynchTask does not reflect on parent thread (who stated this AsynchTask) immediately.

Example --

class MyAsynchTask
{

doInbackground()
{
a = 2;
}

}


int a = 5;

new MyAsynchTask().execute();

// here a still be 5

codercat
  • 22,873
  • 9
  • 61
  • 85
Mufazzal
  • 873
  • 6
  • 12
  • well if you did read my code i did the assignment in the onPostExecute method.. which is supposedly to be running on the UI thread no? – Jack-V Dec 13 '12 at 06:08
  • yes! onPostExecute runs in UI thread but after the completion of doInbackground. – Mufazzal Dec 13 '12 at 07:11
0

Create a interface like OnCompletRequest() then pass this to your ClassB constructor and simply call the method inside this interface such as complete(yourList list) in the method of onPostExecute(String result)

Ali Imran
  • 8,927
  • 3
  • 39
  • 50
-1

You can retrieve the return value of protected Boolean doInBackground() by calling the get() method of AsyncTask class :

E.g. you have AsyncTask class as dbClass like

dbClass bg = new dbClass(this);
String Order_id = bg.execute(constr,data).get();

Here I am passing constr as URL and data as string of inputs to make my class dynamic.

But be careful of the responsiveness of the UI, because get() waits for the computation to complete and will block the UI thread.

kiner_shah
  • 3,939
  • 7
  • 23
  • 37