Search code examples
androidserviceandroid-asynctaskbackground-process

Resuse of Async task code in my various file


I want to create an class file for Async task operation and from creating the object of that class file i want to access these method of async task with no of different class files with different parameters.

Methods of Async task include:-

OnPreExecute()-Want to start progress dialog same for each class.

doInbackground()-Want to perform background operation(like getting data from server) means passing parameter different for each class.

onPostExecute()-Dismiss the progress dialog and update the UI differnt for each class.

Now I'm writing the async task in my every class as inner class like the following:-

class loaddata extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AddNewLineitem.this);
            pDialog.setMessage("Loading Data. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {

                }
            });
            pDialog.show();
        }

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

            try {

                List<NameValuePair> params1 = new ArrayList<NameValuePair>();

                JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
                        "GET", params1);

                compoment = json.getJSONArray(COMPONENT_CODE);

                for (int i = 1; i < compoment.length(); i++) {
                    JSONObject c = compoment.getJSONObject(i);

                    String code = c.getString(CODE);
                    list_compoment.add(code);

                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(String file_url) {

            loadSpinnerData();
            pDialog.dismiss();

        }
    }

And JSON parser class is as follows:-

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if (method == "POST") {
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } else if (method == "GET") {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();

                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;

                HttpGet httpGet = new HttpGet(url);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;


    }
}

And in oncreate() I call this and it works fine:-

new loaddata().execute();

Solution

  • We can reuse Aysntask with different parameters. For this

    1.Create an Interface so that we can reuse,pass and receive parameters

    public interface BackgroundListener {
    
    public Object[] startBackgroundWork(Object... objs);
    public void endBackgroundWork(Object... objs);
    public void beforeBackgroundWork();
    
    
    }
    

    2.Create a Class Extending Asyntask

    BackgroundHandler.java

    import android.os.AsyncTask;
    
    public class BackgroundHandler extends AsyncTask<Object, Object[], Object[]>{
    BackgroundListener backgroundListener;
    
    
    public void setBackgroundListener(BackgroundListener aBackgroundListener)
    {
       this.backgroundListener = aBackgroundListener;
    }
    @Override
     protected void onPreExecute() {
      backgroundListener.beforeBackgroundWork();
    }
    @Override
    protected Object[] doInBackground(Object... objs) {
    
    
    
        return backgroundListener.startBackgroundWork(objs);
    
    }
    
    @Override
    protected void onPostExecute(Object result[]) {
        backgroundListener.endBackgroundWork(result);
    }
    

    }

    Using in Activity

    A.java

    Class A extends Activity implements BackgroundListener
    {
    
       ...onCreate()
       {
    
              BackgroundHandler backgroundHandler =  new BackgroundHandler()         
              backgroundHandler.setBackgroundListner(this);
              backgroundHandler.execute(new Object[]{url1});//pass any number of parameters of any object type 
              // show loading bar
       } 
       public void beforeBackgroundWork()
      {
           pDialog = new ProgressDialog(A.this);
            pDialog.setMessage("Loading Data. Please wait...");
            pDialog.setIndeterminate(false);
            .....
      }
       public Object[] startBackgroundWork(Object... objs)
       {
           // access and type convert the passed parameters like objs[0], objs[1]
          //.... some time consuming stuff
          //.... some time consuming stuff
               String url_foralldropdowns = objs[0].toString();
                List<NameValuePair> params1 = new ArrayList<NameValuePair>();
    
                JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
                        "GET", params1);
    
                JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
                //Create new list_compoment here instead of global declaration
                for (int i = 1; i < compoment.length(); i++) {
                    JSONObject c = compoment.getJSONObject(i);
    
                    String code = c.getString(CODE);
                    list_compoment.add(code);
    
                }
    
    
    
         retrun new Object[]{list_compoment};
       }
       public void endBackgroundWork(Object ...obj)
       {
            pDialog.dismiss();// hide loading bar
           //access resultant parameters like  objs[0], objs[1]
          //user list_component will be in obj[0]
    
       }
    }
    

    Similarly we can reuse in B.java

    Class B extends Activity implements BackgroundListener
    {
    
      ...
     ....
        public void beforeBackgroundWork()
      {
           pDialog = new ProgressDialog(B.this);
            pDialog.setMessage("Loading Data. Please wait...");
            pDialog.setIndeterminate(false);
            .....
      }
       public Object[] startBackgroundWork(Object... objs)
       {
    
       // access and type convert the passed parameters like objs[0], objs[1]
          //.... some time consuming stuff
          //.... some time consuming stuff
               String url2 = objs[0].toString();
                List<NameValuePair> params1 = new ArrayList<NameValuePair>();
    
                JSONObject json = jparser.makeHttpRequest(url2,
                        "GET", params1);
    
                JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
                 //Create new list_compoment here instead of global declaration
                for (int i = 1; i < compoment.length(); i++) {
                    JSONObject c = compoment.getJSONObject(i);
    
                    String code = c.getString(CODE);
                    list_compoment.add(code);
    
                }
    
    
    
         retrun new Object[]{list_compoment};
    
       }
       public void endBackgroundWork(Object ...obj)
       {
          pDialog.dismiss();
           .....
              //user list_component will be in obj[0]
       }
    }