AsyncTask is deprecated? What method used instead of onPreExecute and onPostExecute?

15k views Asked by At

In my old project, I used AsyncTask, but its deprecated so what method i used instead of this? If we used thread, in AsyncTask having onbackground, onPreExecute and onPostExecute Override methods where this sections called in thread. Is there any alternative method. Can you please give me the solution?

Java code:

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

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

        if (paymentSync == null)

            paymentSync = new ReceivePaymentSync(getActivity());

        allCreditCardModel = new AllCreditCardModel();

        allCreditCardModel = paymentSync.getGetCreditCardById(CrediCardId);

        handler.post(allCreditRunnable);

        return null;
    }

    /**
     * @param string
     */
    public void execute(String string) {

        // TODO Auto-generated method stub
    }

    protected void onPreExecute() {

        showProgress();

    }

    @Override
    protected void onPostExecute(String result) {

        progress.dismiss();

    }
}
2

There are 2 answers

5
blackapps On

Just use a Thread.

The onPreExecute code goes in the constructor.

The doInBackground code goes in the run().

The onPostExecute code goes in the run of a runnable for runOnUiThread which you call at the end of the run().

2
zjmo On

This is a simple example, anyway I would give a look to the WorkManager library too:

Executors.newSingleThreadExecutor().execute(() -> {

    Handler mainHandler = new Handler(Looper.getMainLooper());

      //sync calculations

    mainHandler.post(() -> {
      //Update UI
    });

    //other sync calcs.

    mainHandler.post(() -> {
      //Update UI
    });

  });