Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make AsyncTask modular in android

Tags:

android

I am quite new to Android Development. I am working in a app where i need to make a lot of async calls to api. For each and every API call, I have to write the similar looking AsyncTask class over and over again. So, is there any way to make these Async Calls modular?

like image 820
Milan Maharjan Avatar asked May 08 '14 06:05

Milan Maharjan


1 Answers

yes it is possible use Listener and AsyncTask with parameterized constructor

Check it

Create an interface

public interface OnTaskCompletListerner {
 void oncompleteListerner(String name);
}

create an AsyncTask class as follows

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

    private Context context;
    private HashMap<String, String> data;
    private String URL;
    private OnTaskCompletListerner taskdone;

    public AsyncTaskModuler(Context ctx,HashMap<String, String> data,String url,OnTaskCompletListerner taskdone){

        this.context=ctx;
        this.data=data;
        this.URL=url;
        this.taskdone=taskdone;
    }

    @Override
    protected String doInBackground(Void... params) {
        //Do the task here and return the value if needed 
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        taskdone.oncompleteListerner(result);
    }

and call it in your activity like this

public class CallAync extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String url="";
        HashMap<String, String> data=new HashMap<String, String>();
        AsyncTaskModuler moduler=new AsyncTaskModuler(CallAync.this, data, url, completListerner);
        moduler.execute();
    }

    OnTaskCompletListerner completListerner=new OnTaskCompletListerner() {

        @Override
        public void oncompleteListerner(String name) {

        }
    };
}
like image 51
Sainath Patwary karnate Avatar answered Sep 18 '22 14:09

Sainath Patwary karnate