primpap primpap - 3 months ago 9
Android Question

Waiting for a function to finish execution and using the results

Here's the scenario

I have an activity(A) which has a button and textview. I have another class(B) with methods for performing various functions. After creating an instance of class B, one of it's public method is called from A when the button is clicked. The method takes a while to execute(it invokes another time consuming private methods in the class) and returns the value of one of the private members of class B.

The trouble is that the method returns the initial value of the member and not the values after computation. Is there way to force the function to wait for some time and return the value of member of computation?

public String getItem(){
startFunction(); //Time consuming Function
generateItem(); //Function which uses results of startFunction() to generate item and set values to mItem
return mItem; //mItem is the private member of class B

The value returned always is the default value of mItem i.e value set in the constructor. The time taken by startFunction(WiFi Scanning) is arbitrary. Any help would be much appreciated.


When you create an instance of class B make sure it takes Context as an argument in its constructor. Then you can try using AsyncTask (Assuming you know it). Then put the time consuming function in doInBackground() and the function which waits for its values in onPostExecute()