Search code examples
javaandroidgenericsandroid-asynctask

Change the generic return type in doInBackground


Good afternoon, I have a generic baseAsyncTask that works perfectly, java can define the type in doInBackground, but in onPostExecute I call my function doAsync, it is assembling as Object, as I could in creating Override to define the type so I don't Cast

Class DaoProcessorAsync

public abstract class DaoAsyncProcessor<T> {
    public interface DaoProcessCallback<T>{
        void onResult(T result);
    }

    private final DaoProcessCallback daoProcessCallback;

    public DaoAsyncProcessor(DaoProcessCallback daoProcessCallback) {
        this.daoProcessCallback = daoProcessCallback;
    }

    protected abstract T doAsync();

    public void start(){
        new DaoProcessAsyncTask().execute();
    }

    private class DaoProcessAsyncTask extends AsyncTask<Void, Void, T> {

        @Override
        protected T doInBackground(Void... params) {
            return doAsync();
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void onPostExecute(T t) {
            if(daoProcessCallback != null)
                daoProcessCallback.onResult(t);
        }
    }
}  

Call class

new DaoAsyncProcessor<Trabalhador>(new DaoAsyncProcessor.DaoProcessCallback() {
            @Override
            // How to make it explicit that the return is of the Worker type
            public void onResult(Object result) {
                **at that point it returns object to me, and I need to do conversion**
                Trabalhador trabalhador = (Trabalhador) result;
            }
        }){
            @Override
            protected Trabalhador doAsync() {
                **This worker-type return should be explicit in OnRESULT, but I can't define it**
                return trabalhadorDao.lerPorCPF(123);
            }
        }.start();

Solution

  • I think you're missing the type when creating the DaoProcessCallback.

    Try

    new DaoAsyncProcessor<Tabalhador>.DaoProcessCallback()