Reputation: 2771
I have some code in Java/Android. Please take a peek in following code:
@Override
public void onReceive(Context context, Intent intent) {
mInfo.execute();
recentPics= mInfo.getNumberOfRecentPics();
Log.d("LOG", ""+recentPics);
}
mInfo variable is an object of AsyncTask which pulls number of recent pics from web server. They are pulled sucessfully, but the problem is that "LOG" shows old number of recent pics in the currently executed code. For example:
//Receiver execution No1
recentPics = 0;
m.Info.getNumberOfRecentPics() // let's say returns 3
Log.d("LOG", ""+recentPics) // will show 0 at this point of time
//Receiver execution No2
m.Info.getNumberOfRecentPics() // let's say returns 5
Log.d("LOG", ""+recentPics) // will show 3 at this point of time (reads variable from previous execution )
I know that this is because, "LOG" code executes before "getNumberOfRecentPics" method could finish it's work.
Question: My question is simple. How to wait with code execution until "getNumberOfRecentPics" returns with updated number?
EDIT: I heard about object listeners ( Listen for some action ). Do I need to learn how to make them for this occasion or is there another solution?
Upvotes: 0
Views: 99
Reputation: 4574
I would use it this way, just override your onPostExecute where you need it or create a own interface
//create a object f your asyncclass and
//override the onPostExecute where you need it
mInfo = new ASYNCCLASS({
@Override
public void onPostExecute(Object result){
//doSomething
Log.e(...);
}
}).execute();
Waiting is not the answer, because you do not know how long your Asynctask will take to end. Code above is not tested, just pseudoce, but it should show what i mean.
Do not have my IDE round here, so if anybody would correct the brackets if neccessary would be great!
Greetz
Upvotes: 2
Reputation: 8580
I didnt really get what you were trying to do, but i think you can use wait and notify. You could wait on an Object with the thread that runs the Logging, and notify in the thread that does the pics fetching or w\e
Upvotes: 0
Reputation: 248
Maybe the following link could be of interest to you? When I have similar problems, I sometimes use locks in order for a thread to notify another thread, that something important happened.
http://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html
Upvotes: 0