Reputation: 4418
I have an async task class that acts as a wrapper for http requests. I want to be able to either return the data from onPostExecute or somehow specify a method to send that data to after. I can't just call the function explicately because different responses have to go to different methods. Maybe if theres something like a call_user_function from php.
private class Get extends AsyncTask<Void, Void, ContainerData> {
@Override
protected void onPreExecute() {
if (pbTitle != null) {
pbTitle.setVisibility(View.VISIBLE);
}
if (preText != null) {
tvUpdate.setText(preText);
tvUpdate.setVisibility(View.VISIBLE);
}
}
@Override
protected void onProgressUpdate(Void... progress) {
}
//this line will not work, the return type wants to be void
@Override
protected ContainerData onPostExecute(ContainerData obj) {
if (pbTitle != null) {
pbTitle.setVisibility(View.GONE);
}
if (preText != null) {
tvUpdate.setText("");
tvUpdate.setVisibility(View.GONE);
}
updateResponse(obj);
return obj;
}
@Override
protected ContainerData doInBackground(Void... params) {
ContainerData obj = null;
RestClient client = new RestClient(context);
for (Param param : methodParams) {
client.AddParam(param.getKey(), param.getValue());
}
client.setMethod(method);
try {
client.Execute();
} catch (Exception e) {
e.printStackTrace();
}
obj = client.getResponseObject();
return obj;
}
public String updateResponse(ContainerData responseObject) {
try {
// throws API exception
responseObject.checkSuccess();
String message = responseObject.getMessage();
if (message != null) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
dataString = responseObject.getDataString();
} catch (ApiException e) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
return dataString;
}
}
Upvotes: 2
Views: 380
Reputation: 1066
You could define an ICommand interface:
public interface ICommand
{
void execute();
}
And create a new attribute to the Get class
private ICommand command;
public void setCommand(ICommand command)
{
this.command = command
}
Finally when you create the instance, set the command like this:
setCommand(new ICommand() {
@Override
public void execute() {
// Your specific code
}
});
Of course, if you need the ContainerData response data, you can modify ICommand interface so the execute receive the ContainerData instance.
Hope it help! :)
Upvotes: 1
Reputation: 2714
Use Handler. And on post execute send different messages to handler for different response. From the handler you can call different methods.
Upvotes: 0
Reputation: 30825
You've mixed up the ordering in line:
private class Get extends AsyncTask<Void, Void, ContainerData>
The return type goes first. You should have:
private class Get extends AsyncTask<ContainerData, Void, Void>
Upvotes: 0