Google+

Thursday, November 1, 2012

How to Return value from Async task in android

Hi,

After bit R&D, reach on some fatastic solution to get return data from Custom AsyncTask in your activity without using onPostExecute() Method.


Following are the steps to for our Goal.


  • Create your android simple project. 
  • Write "MySampleAsyncTask.java" which extends AsyncTask class. (For example check below class)
MySampleAsyncTask.java

1:  package com.sks.asyncresultback;  
2:  import java.util.Random;  
3:  import android.os.AsyncTask;  
4:  public class MySampleAsyncTask extends AsyncTask<Void, Void, Void> {  
5:       OnAsyncResult onAsyncResult;  
6:       public void setOnResultListener(OnAsyncResult onAsyncResult) {  
7:            if (onAsyncResult != null) {  
8:                 this.onAsyncResult = onAsyncResult;  
9:            }  
10:       }  
11:       @Override  
12:       protected Void doInBackground(Void... params) {  
13:            if (onAsyncResult != null) {  
14:                 // TODO apply your business logic  
15:                 int someNumber = new Random().nextInt(999);  
16:                 if (someNumber % 2 == 0) {  
17:                      onAsyncResult.onResultSuccess(0, "Congratulations\nYou Got Success Value");  
18:                 } else {  
19:                      onAsyncResult.onResultFail(1, "Ohhhhhhhhhhh\n Your Result failed");  
20:                 }  
21:            }  
22:            return null;  
23:       }  
24:       public interface OnAsyncResult {  
25:            public abstract void onResultSuccess(int resultCode, String message);  
26:            public abstract void onResultFail(int resultCode, String errorMessage);  
27:       }  
28:  }  


Look into class

At the bottom of code created a new Interface to code.

public interface OnAsyncResult {  
            public abstract void onResultSuccess(int resultCode, String message);  
            public abstract void onResultFail(int resultCode, String errorMessage);  
       }

You are free to use this listener. Here I didn't use onPostExecute() Method. so you can use your business logic as per your way.



  • Now lets Create your "MainActivity.java" from which we are calling our MySampleAsyncTask for our purpose.

1:  public class MainActivity extends Activity {  
2:       public TextView textView;  
3:       MySampleAsyncTask asyncTask;  
4:       @Override  
5:       public void onCreate(Bundle savedInstanceState) {  
6:            super.onCreate(savedInstanceState);  
7:            setContentView(R.layout.activity_main);  
8:            textView = (TextView) findViewById(R.id.tv_Result);  
9:            findViewById(R.id.btn_clickMe).setOnClickListener(new OnClickListener() {  
10:                 @Override  
11:                 public void onClick(View v) {  
12:                      asyncTask = new MySampleAsyncTask();  
13:                      asyncTask.setOnResultListener(asynResult);  
14:                      asyncTask.execute();  
15:                 }  
16:            });  
17:       }  
18:       OnAsyncResult asynResult = new OnAsyncResult() {  
19:            @Override  
20:            public void onResultSuccess(final int resultCode, final String message) {  
21:                 // need to add this part in ui thread.  
22:                 // as you will then thread exception.  
23:                 runOnUiThread(new Runnable() {  
24:                      public void run() {  
25:                           textView.setText("Code : " + resultCode + "\nMessage : " + message);  
26:                      }  
27:                 });  
28:            }  
29:            @Override  
30:            public void onResultFail(final int resultCode, final String errorMessage) {  
31:                 // need to add this part in ui thread.  
32:                 // as you will then thread exception.  
33:                 runOnUiThread(new Runnable() {  
34:                      public void run() {  
35:                           textView.setText("Code : " + resultCode + "\nMessage : " + errorMessage);  
36:                      }  
37:                 });  
38:            }  
39:       };  

at the last block we have create instance of OnAsynkResult listener and set to our MySampleAsyncTask object on Button Click.


18:      OnAsyncResult asynResult = new OnAsyncResult() {  
19:            @Override  
20:            public void onResultSuccess(final int resultCode, final String message) {  
21:                 // need to add this part in ui thread.  
22:                 // as you will then thread exception.  
23:                 runOnUiThread(new Runnable() {  
24:                      public void run() {  
25:                           textView.setText("Code : " + resultCode + "\nMessage : " + message);  
26:                      }  
27:                 });  
28:            }  
29:            @Override  
30:            public void onResultFail(final int resultCode, final String errorMessage) {  
31:                 // need to add this part in ui thread.  
32:                 // as you will then thread exception.  
33:                 runOnUiThread(new Runnable() {  
34:                      public void run() {  
35:                           textView.setText("Code : " + resultCode + "\nMessage : " + errorMessage);  
36:                      }  
37:                 });  
38:            }  
39:       };



on each method, if you want to set values to view then you have to use runOnUiThread methods.
as this listeners are already calling from thread.




Download Source Code

Check our Source code 

svn checkout 
http://smartphone-app-by-sachin-shelke.googlecode.com/svn/trunk/


Comments are always welcome.




Google+