android - How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class? - Stack Overflow

0

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

38 ANSWERS

0

(Jinjo) Says: Code Snippet Found!


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); 
    }

}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


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);

}       

}   

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


public interface AsyncResponse {
    void processFinish(String output);
}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


public class MyAsyncTask extends AsyncTask{
  public AsyncResponse delegate = null;

    @Override
    protected void onPostExecute(String result) {
      delegate.processFinish(result);
    }
 }

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


public class MainActivity implements AsyncResponse{
  MyAsyncTask asyncTask =new MyAsyncTask();

  @Override
  public void onCreate(Bundle savedInstanceState) {

     //this to set delegate/listener back to this class
     asyncTask.delegate = this;

     //execute the async task 
     asyncTask.execute();
  }

  //this override the implemented method from asyncTask
  @Override
  void processFinish(String output){
     //Here you will receive the result fired from async class 
     //of onPostExecute(result) method.
   }
 }

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


public class MyAsyncTask extends AsyncTask{

  // you may separate this or combined to caller class.
  public interface AsyncResponse {
        void processFinish(String output);
  }

  public AsyncResponse delegate = null;

    public MyAsyncTask(AsyncResponse delegate){
        this.delegate = delegate;
    }

    @Override
    protected void onPostExecute(String result) {
      delegate.processFinish(result);
    }
}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


public class MainActivity extends Activity {

   MyAsyncTask asyncTask =new MyAsyncTask(new AsyncResponse(){

     @Override
     void processFinish(String output){
     //Here you will receive the result fired from async class 
     //of onPostExecute(result) method.
     }
  }).execute();

 }

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


public class MainActivity extends Activity 
    implements AsyncResponse{

    @Override
    public void onCreate(Bundle savedInstanceState) {

        //execute the async task 
        new MyAsyncTask(this).execute();
    }

    //this override the implemented method from AsyncResponse
    @Override
    void processFinish(String output){
        //Here you will receive the result fired from async class 
        //of onPostExecute(result) method.
    }
}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


public class MyActivity extends Activity {
    // existing Activity code
    ...

    private class MyAsyncTask extends AsyncTask<String, Void, String> {
        // existing AsyncTask code
        ...
    }
}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


public class MyAsyncTask extends AsyncTask<String, Void, String> {
    private Activity activity;

    public MyAsyncTask(Activity activity) {
        this.activity = activity;
    }

    // existing AsyncTask code
    ...
}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


try {
    String receivedData = new AsyncTask().execute("http://yourdomain.com/yourscript.php").get();
} 
catch (ExecutionException | InterruptedException ei) {
    ei.printStackTrace();
}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


public interface AsyncResponse {
    void processFinish(Object output);
}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


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[] { "Your request to aynchronous task class is giving here.." });


            }
        });

    }



}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


new AasyncTask()
{
    @Override public void onPostExecute(String result)
    {
       // do whatever you want with result 
    }
}.execute(a.targetServer);

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


myTask.execute("url");
String result = "";
try {
      result = myTask.get().toString();
} catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
}catch (ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


// TASK 
public class SomeClass extends AsyncTask<Void, Void, String>>
{

    private OnTaskExecutionFinished _task_finished_event;

    public interface OnTaskExecutionFinished
    {
        public void OnTaskFihishedEvent(String Reslut);
    }

    public void setOnTaskFinishedEvent(OnTaskExecutionFinished _event)
    {
        if(_event != null)
        {
            this._task_finished_event = _event;
        }
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();

    }

    @Override
    protected String doInBackground(Void... params)
    {
        // do your background task here ...

        return "Done!";
    }

    @Override
    protected void onPostExecute(String result)
    {
        super.onPostExecute(result);
        if(this._task_finished_event != null)
        {
            this._task_finished_event.OnTaskFihishedEvent(result);
        }
        else
        {
            Log.d("SomeClass", "task_finished even is null");
        }
    }
}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


// MAIN ACTIVITY
public class MyActivity extends ListActivity
{
   ...
    SomeClass _some_class = new SomeClass();
    _someclass.setOnTaskFinishedEvent(new _some_class.OnTaskExecutionFinished()
    {
    @Override
    public void OnTaskFihishedEvent(String result)
    {
        Toast.makeText(getApplicationContext(),
                "Phony thread finished: " + result,
                Toast.LENGTH_SHORT).show();
    }

   });
   _some_class.execute();
   ...
 }

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


public interface myAsyncTaskCompletedListener {
    void onMyAsynTaskCompleted(int responseCode, String result);
}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


public class myAsyncTask extends AsyncTask<String, Void, String> {

    private myAsyncTaskCompletedListener listener;
    private int responseCode = 0;

    public myAsyncTask() {
    }

    public myAsyncTask(myAsyncTaskCompletedListener listener, int responseCode) {
        this.listener = listener;
        this.responseCode = responseCode;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }


    @Override
    protected String doInBackground(String... params) {
        String result;
        String param = (params.length == 0) ? null : params[0];
        if (param != null) {
            // Do some background jobs, like httprequest...
            return result;
        }
        return null;
    }

    @Override
    protected void onPostExecute(String finalResult) {
        super.onPostExecute(finalResult);
        if (!isCancelled()) {
            if (listener != null) {
                listener.onMyAsynTaskCompleted(responseCode, finalResult);
            }
        }
    }
}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


public class MainActivity extends AppCompatActivity implements myAsyncTaskCompletedListener {

    @Override
    public void onMyAsynTaskCompleted(int responseCode, String result) {

        switch (responseCode) {
            case TASK_CODE_ONE: 
                // Do something for CODE_ONE
                break;
            case TASK_CODE_TWO:
                // Do something for CODE_TWO
                break;
            default: 
                // Show some error code
        }        
    }

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Some other codes...
        new myAsyncTask(this,TASK_CODE_ONE).execute("Data for background job");
        // And some another codes...
}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


public class MainActivity extends Activity 
{

@Override
public void onCreate(Bundle savedInstanceState) {

    //execute the async task 
    MyAsyncTask task = new MyAsyncTask(){
            protected void onPostExecute(String result) {
                //Do your thing
            }       

    }

    task.execute("Param");

}


}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


public interface MyTaskInformer {

    void onTaskDone(String output);

}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


public class MySmallAsyncTask extends AsyncTask<String, Void, String> {

    // ***** Hold weak reference *****
    private WeakReference<MyTaskInformer> mCallBack;

    public MySmallAsyncTask(MyTaskInformer callback) {
        this.mCallBack = new WeakReference<>(callback);
    }

    @Override
    protected String doInBackground(String... params) {

        // Here do whatever your task is like reading/writing file
        // or read data from your server or any other heavy task

        // Let us suppose here you get response, just return it
        final String output = "Any out, mine is just demo output";

        // Return it from here to post execute
        return output;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        // Here you can't guarantee that Activity/Fragment is alive who started this AsyncTask

        // Make sure your caller is active

        final MyTaskInformer callBack = mCallBack.get();

        if(callBack != null) {
            callBack.onTaskDone(s);
        }
    }
}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


public class MainActivity extends Activity implements MyTaskInformer {

    private TextView mMyTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mMyTextView = (TextView) findViewById(R.id.tv_text_view);

        // Start your AsyncTask and pass reference of MyTaskInformer in constructor
        new MySmallAsyncTask(this).execute();
    }

    @Override
    public void onTaskDone(String output) {

        // Here you will receive output only if your Activity is alive.
        // no need to add checks like if(!isFinishing())

        mMyTextView.setText(output);
    }
}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


   private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        loadingdialog.dismiss();

    }
    };

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


 public void startUpload(String filepath) {
    loadingdialog = ProgressDialog.show(MainActivity.this, "Uploading", "Uploading Please Wait", true);
    final String _path = filepath;
    new Thread() {
        public void run() {
            try {
                UploadFile(_path, getHostName(), getPortNo());
                handler.sendEmptyMessage(0);

            } catch (Exception e) {
                Log.e("threadmessage", e.getMessage());
            }
        }
    }.start();
}

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


String result = new myAsyncTask ().execute ().get ();

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


OnPostExecute()
Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


static
Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


public static String dataFromAsyncTask;
Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


MyTaskInformer.java
Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


MySmallAsyncTask.java
Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


MainActivity.java
Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


doInBackground ()
Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


onPostExecute ()
Add Comment

COMMENTS
No comments yet
0

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 helps

Add Comment

COMMENTS
No comments yet
0

(Jinjo) Says: Code Snippet Found!


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 helps

Add Comment

COMMENTS
No comments yet

Original page: https://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a

Do you Like pparser?
Download Now