Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncTask return value

My android app connects to my website to retrieve and upload information so I use an AsyncTask thread.

In one instance, I need my thread to return a true or a false value to my main thread.

Is there a way to get this return value from an AsyncTask execute function?

When I do the following:

Toast.makeText(Locate.this, "Testing : "+locationUpdate.execute(location), Toast.LENGTH_LONG).show(); 

I just get alot of gibberish.

I think what I need is a means to pause the main thread until the second thread completes. The second thread calls a function in the main thread to set my return value. So when the second thread completes, the main thread can unpause and access the return value as set by the second thread If this logic is sound, please offer suggestions ... thanks!

like image 968
sisko Avatar asked Mar 28 '11 10:03

sisko


People also ask

How do I get return value from doInBackground?

You can retreive the return value of protected Boolean doInBackground() by calling the get() method of AsyncTask class : AsyncTaskClassName task = new AsyncTaskClassName(); bool result = task.

How do I return from async task?

If you use a Task return type for an async method, a calling method can use an await operator to suspend the caller's completion until the called async method has finished. In the following example, the WaitAndApologizeAsync method doesn't contain a return statement, so the method returns a Task object.

Why did AsyncTask get deprecated?

This class was deprecated in API level 30. AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.

What is the replacement of AsyncTask?

Alternative 1: Using Executor and Handler The executor will help in performing any task in the background and the handler will help to make UI changes.


1 Answers

You can use AsyncTask get() method for this. It waits if necessary for the computation to complete, and then retrieves its result:

Toast.makeText(Locate.this, "Testing : " + locationUpdate.execute(location).get(), Toast.LENGTH_LONG).show(); 

But be sure to not block the main thread for a long period of time, as this will lead to unresponsive UI and ANR.

UPDATE
I missed the point that question was about async web download/upload. Web/network operation should considered as a long one and thus the approach "pause UI thread and wait till download finishes" is always a wrong one. Use usual result publishing approach intstead (e.g.: AsyncTask.onPostExecute, Service + sendBroadcast, libraries like Volley, RoboSpice, DataDroid etc).

like image 124
Idolon Avatar answered Oct 04 '22 07:10

Idolon