Monday, April 9, 2012

Android AsyncTask example: how to pass different or multiple objects

How to implement AsyncTask:

               public class AsyncTaskExample extends AsyncTask<Object, Void, Boolean> {
                             
                              @Override
                              protected Boolean doInBackground(Object... params) {
                                             String s = (String) params[0];
                                             Long lValue = (Long) params[1];
                                             Integer iValue = (Integer) params[2];
                                             Boolean bValue = (Boolean) params[3];
                                             // do something useful
                                             return new Boolean(true);
                              }
                             
                              @Override
                              protected void onPostExecute(Boolean result) {
                                             // do something useful
                              }
               }

How to use AsyncTask:
             new AsyncTaskExample().execute("Hello World", new Long(12345),
                           new Integer(12345), new Boolean(true));

------------------------------------------------------------

OR

How to implement AsyncTask:

               public class AsyncTaskExample extends AsyncTask<Void, Void, Boolean> {

                              private String s;
                              private Long lValue;
                              private Integer iValue;
                              private Boolean bValue;
                             
                              public AsyncTaskExample(String s, Long lValue, Integer iValue, Boolean bValue)
        {
            this.s = s;
            this.lValue = lValue;
            this.iValue = iValue;
            this.bValue = bValue;
        }
                             
                              @Override
                              protected Boolean doInBackground(Void... params) {
                                             // do something useful
                                             return new Boolean(true);
                              }
                             
                              @Override
                              protected void onPostExecute(Boolean result) {
                                             // do something useful
                              }
               }
How to use AsyncTask:



             new AsyncTaskExample("Hello World", new Long(12345),
                           new Integer(12345), new Boolean(true)).execute();


1 comment:

  1. Awesome . This is exactly what i am looking for .Thanks for your help

    ReplyDelete