Async Android applications, should I create three different classes?

advertisements

I'm a beginner in Java and coding for Android. When I was coding an app which makes some network requests, I got NetworkOnMainThreadException exception. I googled and found out the reason and solution. But I still have a question. My app makes requests on different sites and will does different actions with responses (first response on login action, it will be checked, second action is some api calls, third action is requesting images), I think I should not make three different classes for each case (doInBackground is the same, but different onPostExecute methods will be here). How can I fix this problem? Thanks


You can pass an aditional variable as doInBackground Params, save it as "global" class variable and switch in onPostExecute so u dont have to make 3 different classes

Like this

public class Async_DL extends AsyncTask<String, String, String> {
    String type_of_request;
    String url;

    @Override
    protected void onPreExecute(){
    }

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

        this.url = params[0];
        this.type_of_request = params[1];

        doinBackground stuff....
    }

    @Override
    protected void onPostExecute(String result) {
        switch(this.type_of_request){
            case a:
                do some stuff
            break;
        }
    }

}