Home » Android » AsyncTask already finished [duplicate]

AsyncTask already finished [duplicate]

Posted by: admin November 1, 2017 Leave a comment

Questions:

This question already has an answer here:

Answers:

A cleaner way to do it is to use interfaces as listeners.
Create this interface:

public interface OnAsyncFinished{
    void onAsyncFinished(Object o);
}

Add the interface as a parameter in your AsyncTaskClass constructor:

private OnAsyncFinished onAsyncFinished;
public UpdateProfile(..., OnAsyncFinished onAsyncFinished) {
   ...
   this.onAsyncFinished = onAsyncFinished;
}
...
@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    onAsyncFinished.onAsyncFinished(s); //This will notifiy the method on main activity, and you can now resume the work there
    ...
}

Implement the interface in your main activity:

public MainActivity extends Activity implements OnAsyncFinished {
     @Override
     public void onAsyncFinished(Object o) {
         //This will get called after onPostExecute, do what u want with the object you got from onPostExecute, json or string in ur example
         profileDefaults(); //call ur function
     }
}

EDIT:
When creating the async task in your main activity pass this in the constructor likeso:

        @Override
        public void run() {
            new UpdateProfile(..., this).execute(Urls.GET_USER);
        }