Using delegates for AsyncTask - android

I'm having trouble implementing a delegate in my android app.
In my GetData class I have nested asynctask, and I need to notify my main activity when all the work has actually finished.
I came up with this answer from Mohd Mufiz
What is the best way for AsyncTask to notify parent Activity about completion?
But I always get stuck at the same point:
in my GetData class I call a constructor with the delegate as only argument:
public class GetData {
private TaskDelegate delegate;
public GetData(TaskDelegate delegate) {
this.delegate = delegate;
}
...
}
In my main activity I don't know what I have to pass to get it working:
GetData getData = new GetData(**???**);

Going from the question you linked to, that defined TaskDelegate as :
public interface TaskDelegate {
public void taskCompletionResult(String result);
}
You can pass GetData any instance of a class that implements TaskDelegate - but typically, that would be the object that creates it - ie. your main activity (and so, therefore, it would also implement "void taskCompletionResult(String result);"). That then means you can pass "this" to GetData's constructor, so :
public class MyMainActivity implements TaskDelegate {
public void someMethod() {
GetData getData = new GetData(this);
}
public void taskCompletionResult(String result) {
// do stuff
}
}

Related

Substitute for activity argument when calling a class from AsyncTask

here's a portion of my code:
public class Login extends Activity {
private class LoginUser extends AsyncTask<String, String, Boolean> {
#Override
protected void onPostExecute(Boolean returnResult) {
DialogSelectAccount dsa=new DialogSelectAccount(getParent());
dsa.show();
}
}
}
public class DialogSelectAccount extends Dialog implements android.view.View.OnClickListener {
public DialogSelectAccount(Activity a) {
super(a);
}
}
but when I run the app, it get a NPE error at the "super(a)" under the public DialogSelectAccount();
but when I changed my code to
public class Login extends Activity {
private class LoginUser extends AsyncTask<String, String, Boolean> {
#Override
protected void onPostExecute(Boolean returnResult) {
test();
}
}
public void test(){
DialogSelectAccount dsa=new DialogSelectAccount(this);
dsa.show();
}
}
it works. So what if I don't want to create a separate method like above and calls DialogSelectAccount directly inside the onPostExecute, what should I pass as the argument?
Thanks
So what if I don't want to create a separate method like above and calls DialogSelectAccount directly inside the onPostExecute, what should I pass as the argument?
answer:
DialogSelectAccount dsa=new DialogSelectAccount(Login.this);
This is rather general java question, for more on inner classes read here: Getting hold of the outer class object from the inner class object
The dialog class needs a Context attribute.
When you say getParent() - I suppose it does not return context.
You can keep the context attribute in a global class and retrieve it - though I will not recommend that.

How to call Activity method in an AsyncTask

I would like to call an Activity method after the onPostExecute of my AsyncTask.
Do you know how I can do that?
I want to call in the sendSMS(String phoneNumber, String message) method in the onPostExecute.
One way is to pass an instance of the Activity through PostTask constructor, something like:
private class PostTask extends AsyncTask<String, Integer, String>
{
private AsyncBigCalculActivity activity;
public PostTask(AsyncBigCalculActivity activity)
{
this.activity = activity;
}
// ...
}
and on creating the PostTask instance, pass the activity instance:
new PostTask(this).execute();
Now you can invoke sendSMS() from within PostTask, like:
activty.sendSMS(...);
Also note that if you are defining the PostTask as a private class inside the activty, then you can invoke sendSMS() like:
AsyncBigCalculActivity.this.sendSMS(...);
Add a constructor and a global variable to your AsyncTask like this:
AsyncBigCalculActivity mActivity;
public PostTask(AsyncBigCalculActivity a) {
mActivity = a;
}
Then simply use mActivity.sendSMS("test", "test") when you need it.
However, you should really have methods like sendSMS() in a utility class.
If your AsyncTask is an inner class of your Activity then you should be able to call the Activity method from your onPostExecute(). Otherwise, you can send the Context to a constructor of your AsyncTask and uses that to call the method
Write a Callback
You can create a CallBack using an interface. This way you can use your AsyncTask with any activity. (Loosely coupled code)
1) Create a Callback
interface MyAsyncTaskCallBack{
public void doStuff(String arg1,String arg2);
}
2) Initialize the callback in your AsyncTask
private class MyTask extends AsyncTask<String, Void, Void>
{
private MyAsyncTaskCallBackactivity callback;
public MyTask(MyAsyncTaskCallBackactivity callback)
{
this.callback = callback;
}
//Call callback.doStuff(....phonenum, ....message); in your postExecute
}
3) Implement the Callback in your Activity and override doStuff() method
public YourActivity extends AppCompatActivity implements MyAsyncTaskCallBack{
// Your Activity code
// new MyTask(this).execute("phonenum","msg"); //<--- This is how you run AsyncTask
private void sendMessage(String num, String msg){
// send msg logic
}
#Override
public void doStuff(String arg1,String arg2){
sendMessage(arg1,arg2); // invoke activity method
}
}

android asynctask sending callbacks to ui [duplicate]

This question already has answers here:
How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?
(17 answers)
Closed 6 years ago.
I have the following asynctask class which is not inside the activity. In the activity I'm initializing the asynctask, and I want the asynctask to report callbacks back to my activity.
Is it possible? Or does the asynctask must be in the same class file as the activity?
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
caller.sometextfield.setText("bla");
}
Something like this?
You can create an interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute()
For example:
Your interface:
public interface OnTaskCompleted{
void onTaskCompleted();
}
Your Activity:
public class YourActivity implements OnTaskCompleted{
// your Activity
}
And your AsyncTask:
public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
private OnTaskCompleted listener;
public YourTask(OnTaskCompleted listener){
this.listener=listener;
}
// required methods
protected void onPostExecute(Object o){
// your stuff
listener.onTaskCompleted();
}
}
EDIT
Since this answer got quite popular, I want to add some things.
If you're a new to Android development, AsyncTask is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:
Possibility of memory leaks. If you keep reference to your Activity, it will stay in memory even after user left the screen (or rotated the device).
AsyncTask is not delivering result to Activity if Activity was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.
Convoluted code which does everything in Activity
When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.
I felt the below approach is very easy.
I have declared an interface for callback
public interface AsyncResponse {
void processFinish(Object output);
}
Then created asynchronous Task for responding all type of parallel requests
public class MyAsyncTask extends AsyncTask<Object, Object, Object> {
public AsyncResponse delegate = null;//Call back interface
public MyAsyncTask(AsyncResponse asyncResponse) {
delegate = asyncResponse;//Assigning call back interfacethrough constructor
}
#Override
protected Object doInBackground(Object... params) {
//My Background tasks are written here
return {resutl Object}
}
#Override
protected void onPostExecute(Object result) {
delegate.processFinish(result);
}
}
Then Called the asynchronous task when clicking a button in activity Class.
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
Button mbtnPress = (Button) findViewById(R.id.btnPress);
mbtnPress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyAsyncTask asyncTask =new MyAsyncTask(new AsyncResponse() {
#Override
public void processFinish(Object output) {
Log.d("Response From Asynchronous task:", (String) output);
mbtnPress.setText((String) output);
}
});
asyncTask.execute(new Object[] { "Youe request to aynchronous task class is giving here.." });
}
});
}
}
Thanks
IN completion to above answers, you can also customize your fallbacks for each async call you do, so that each call to the generic ASYNC method will populate different data, depending on the onTaskDone stuff you put there.
Main.FragmentCallback FC= new Main.FragmentCallback(){
#Override
public void onTaskDone(String results) {
localText.setText(results); //example TextView
}
};
new API_CALL(this.getApplicationContext(), "GET",FC).execute("&Books=" + Main.Books + "&args=" + profile_id);
Remind: I used interface on the main activity thats where "Main" comes, like this:
public interface FragmentCallback {
public void onTaskDone(String results);
}
My API post execute looks like this:
#Override
protected void onPostExecute(String results) {
Log.i("TASK Result", results);
mFragmentCallback.onTaskDone(results);
}
The API constructor looks like this:
class API_CALL extends AsyncTask<String,Void,String> {
private Main.FragmentCallback mFragmentCallback;
private Context act;
private String method;
public API_CALL(Context ctx, String api_method,Main.FragmentCallback fragmentCallback) {
act=ctx;
method=api_method;
mFragmentCallback = fragmentCallback;
}
I will repeat what the others said, but will just try to make it simpler...
First, just create the Interface class
public interface PostTaskListener<K> {
// K is the type of the result object of the async task
void onPostTask(K result);
}
Second, create the AsyncTask (which can be an inner static class of your activity or fragment) that uses the Interface, by including a concrete class. In the example, the PostTaskListener is parameterized with String, which means it expects a String class as a result of the async task.
public static class LoadData extends AsyncTask<Void, Void, String> {
private PostTaskListener<String> postTaskListener;
protected LoadData(PostTaskListener<String> postTaskListener){
this.postTaskListener = postTaskListener;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null && postTaskListener != null)
postTaskListener.onPostTask(result);
}
}
Finally, the part where your combine your logic. In your activity / fragment, create the PostTaskListener and pass it to the async task. Here is an example:
...
PostTaskListener<String> postTaskListener = new PostTaskListener<String>() {
#Override
public void onPostTask(String result) {
//Your post execution task code
}
}
// Create the async task and pass it the post task listener.
new LoadData(postTaskListener);
Done!

how to pass the result of asynctask onpostexecute method into the parent activity android

I am developing an application in which i need to send the value of the asynctask's onPostExecute method's result in to the previous activity , ie the activity in which the aync task is being called.pls put some codes. Anyhelp is appreciated
Two ways:
Declare class extending AsyncTask as private class in parent Activity
Pass Handler or Activity itself as param of class extending AsyncTask
If I were you, I'd follow the first option.
Look at DOCS:
class MyActivitySubclass extends Activity {
function runOnPostExecute(){
// whatever
}
private class MyTask extends AsyncTask<Void, Void, Void> {
void doInBackground(Void... params){
// do your background stuff
}
void onPostExecute(Void... result){
runOnPostExecute();
}
}
}
Note 1
Code placed in body of function onPostExecute is already run on Activity thread, you should just mention that this keywords leads to MyTask.this and not MyActivitySubclass.this
Well if your AsyncTask is an inner class, you could simply call a method in your activity from onPostExecute():
public class MyActivity extends Activity {
public void someMethod(String someParam) {
// do something with string here
}
public class InnerTask extends AsyncTask<...> {
protected void onPostExecute(result) {
someMethod(Send parameters);
}
}
}
The onPostExecute method is fired on the main UI thread, so anything done there is already on the AsyncTasks caller.
http://developer.android.com/reference/android/os/AsyncTask.html
Fire an event in the OnPostExecute.
Its an add on to the answer by Marek Sebera, he pointed to use a handler. To keep the code simple and intuitive use an interface. This isn't alien concept, we use it all the time for callback functions (eg: OnClickListner etc..). The code would look some thing like this.
public class InnerTask extends AsyncTask<...>
{
interface ResultHandler
{
void gotResult(<> result);
}
private ResultHandler myResult;
//constructor
public InnerTask(....params...,ResultHandler callback)
{
...
this.myResult = callback;
}
protected void onPostExecute(<>result)
{
...
myResult.gotResult(result);
}
}
public class MyActivity extends Activity implements InnerTask.ResultHandler
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
//do something
//if you want the InnerTask to execute here
InnerTask i = new InnerTask(....params...,this); //send 'this' as parameter
i.execute();
}
#Override
public void gotResult(<> result)
{
//from onPostExecute
}
}
If we want to use the same AsynTask class at multiple sites we can use this type of implementation instead of using nested classes implementation.

Async Task Data fetcher

I have one class that extends Asynctask. In this class I have a method that returns a hash map. How can I get this Hashmap in different class that extends Activity.
Anyone give me some reference code?
You can create a listener in your Activity, then pass this listener into your AsyncTask. Once the AsyncTask completes you can call the listener to set the Hashmap. So in your AsyncTask create your listener:
public static interface MyListener {
void setHashmap(Hashmap myHashmap);
}
Also, have a function to set your listener:
public void setListener(MyListener listener) {
this.listener = listener;
}
Then in onPostExecute call the function on your listener
listener.setHashmap(myHashmap);
In your activity implement this listener:
public class MyActivity extends Activity implements MyListener { ...
public void setHashmap(Hashmap hashmap) {
// do stuff here
this.hash = hashmap
}
Then finally set your listener and start your AsyncTask:
AsyncTask task = new MyAsyncTask();
task.setListener(this);
task.execute();
Of course you could also just put your AsyncTask in your Activity then you can set the hashmap in onPostExecute.

Categories

Resources