I have this two classes. My main Activity and the one that extends the AsyncTask
, Now in my main Activity I need to get the result from the OnPostExecute()
in the AsyncTask
. How can I pass or get the result to my main Activity?
Here is the sample codes.
My main Activity.
public class MainActivity extends Activity{
AasyncTask asyncTask = new AasyncTask();
@Override
public void onCreate(Bundle aBundle) {
super.onCreate(aBundle);
//Calling the AsyncTask class to start to execute.
asyncTask.execute(a.targetServer);
//Creating a TextView.
TextView displayUI = asyncTask.dataDisplay;
displayUI = new TextView(this);
this.setContentView(tTextView);
}
}
This is the AsyncTask class
public class AasyncTask extends AsyncTask<String, Void, String> {
TextView dataDisplay; //store the data
String soapAction = "http://sample.com"; //SOAPAction header line.
String targetServer = "https://sampletargeturl.com"; //Target Server.
//SOAP Request.
String soapRequest = "<sample XML request>";
@Override
protected String doInBackground(String... string) {
String responseStorage = null; //storage of the response
try {
//Uses URL and HttpURLConnection for server connection.
URL targetURL = new URL(targetServer);
HttpURLConnection httpCon = (HttpURLConnection) targetURL.openConnection();
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setUseCaches(false);
httpCon.setChunkedStreamingMode(0);
//properties of SOAPAction header
httpCon.addRequestProperty("SOAPAction", soapAction);
httpCon.addRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpCon.addRequestProperty("Content-Length", "" + soapRequest.length());
httpCon.setRequestMethod(HttpPost.METHOD_NAME);
//sending request to the server.
OutputStream outputStream = httpCon.getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
writer.write(soapRequest);
writer.flush();
writer.close();
//getting the response from the server
InputStream inputStream = httpCon.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
ByteArrayBuffer byteArrayBuffer = new ByteArrayBuffer(50);
int intResponse = httpCon.getResponseCode();
while ((intResponse = bufferedReader.read()) != -1) {
byteArrayBuffer.append(intResponse);
}
responseStorage = new String(byteArrayBuffer.toByteArray());
} catch (Exception aException) {
responseStorage = aException.getMessage();
}
return responseStorage;
}
protected void onPostExecute(String result) {
aTextView.setText(result);
}
}
in your Oncreate():
`
}`
Why do people make it so hard.
This should be sufficient.
Do not implement the onPostExecute on the async task, rather implement it on the Activity:
try this:
And usage example:
You can call the
get()
method ofAsyncTask
(or the overloadedget(long, TimeUnit)
). This method will block until theAsyncTask
has completed its work, at which point it will return you theResult
.It would be wise to be doing other work between the creation/start of your async task and calling the
get
method, otherwise you aren't utilizing the async task very efficiently.This answer might be late but I would like to mention few things when your
Activity
dependent onAsyncTask
. That would help you in prevent crashes and memory management. As already mentioned in above answers go withinterface
, we also say them callbacks. They will work as an informer, but never ever send strong reference ofActivity
orinterface
always use weak reference in those cases.Please refer to below screenshot to findout how that can cause issues.
As you can see if we started
AsyncTask
with a strong reference then there is no guarantee that ourActivity
/Fragment
will be alive till we get data, so it would be better to useWeakReference
in those cases and that will also help in memory management as we will never hold the strong reference of ourActivity
then it will be eligible for garbage collection after its distortion.Check below code snippet to find out how to use awesome WeakReference -
MyTaskInformer.java
Interface which will work as an informer.MySmallAsyncTask.java
AsyncTask to do long running task, which will useWeakReference
.MainActivity.java
This class is used to start myAsyncTask
implementinterface
on this class andoverride
this mandatory method.Easy:
Create
interface
class, whereString output
is optional, or can be whatever variables you want to return.Go to your
AsyncTask
class, and declare interfaceAsyncResponse
as a field :In your main Activity you need to
implements
interfaceAsyncResponse
.UPDATE
I didn't know this is such a favourite to many of you. So here's the simple and convenience way to use
interface
.still using same
interface
. FYI, you may combine this intoAsyncTask
class.in
AsyncTask
class :do this in your
Activity
classOr, implementing the interface on the Activity again
As you can see 2 solutions above, the first and third one, it needs to create method
processFinish
, the other one, the method is inside the caller parameter. The third is more neat because there is no nested anonymous class. Hope this helpsTip: Change
String output
,String response
, andString result
to different matching types in order to get different objects.