0

Method doInBackground() works well, but never call onPostExecute(). Method onPostExecute() override right, I do not cancel the AsyncTask and start the task with execute() method. I can not understand that behaviour.

Start the task:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    httpClient = new HttpClient();
    new GetRepositoriesAsyncTask().execute("android");
}

Async class:

 private class GetRepositoriesAsyncTask extends AsyncTask<String, Integer, ArrayList<Repository>>{
        @Override
        protected ArrayList<Repository> doInBackground(String... queries) {
            try {
                return httpClient.getRepositories(queries[0]);
            } catch (IOException | JSONException e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(ArrayList<Repository> repositories) {
            if (repositories != null) {
                adapter.addItems(repositories);
            } else {
                Toast.makeText(MainActivity.this, R.string.error, Toast.LENGTH_SHORT).show();
            }
        }
    }

Thanks

  • Does `httpClient.getRepositories()` ever return? Also, AsyncTask has been deprecated and you should really use an alternative: https://developer.android.com/reference/android/os/AsyncTask. – Dan Harms May 17 '22 at 21:24
  • I suggest to use Kotlin Coroutines as an alternative https://stackoverflow.com/a/62748880/1731626. You can create an extension function `CoroutineScope.executeAsyncTask(...)` and call it in `ViewModel` like the following `viewModelScope.executeAsyncTask(...)` or in `Activity`/`Fragment` `lifecycleScope.executeAsyncTask(...)`. – Sergio May 18 '22 at 07:17
  • thank you, change AsynTask to java.util.concurrent helps me! – Studene008 May 18 '22 at 09:30

0 Answers0