Android AsyncTask - why doInBackground () fails?

I have a nested fragment containing the following method:

public void onSave() { if (getActivity() == null || view == null) return; if (file != null && file.exists()) { new AsyncTask<Void, Void, Void>() { @Override protected void onPreExecute() { Log.d("log", "onPreExecute of save ex"); } @Override protected Void doInBackground(Void... params) { Log.d("log", "doInBackground of save ex"); //DO SOMETHING return null; } protected void onPostExecute(Void result) { BaseFragment fragment = new LocalListFragment(); ((LocalLauncherFragment)(LocalEditFragment.this.getParentFragment())).setFragment(fragment); Log.d("log", "end of save ex"); }; }.execute(); } else { showAlert(); } } 

My problem is that if I call this method for the first time, it will execute until onPostExecute (). However, if I move to another fragment and reopen this fragment (by creating a new fragment object and replacing it), then only onPreExecute () is executed. Why is this asyncTask not executing a second time?

Intentionally, if I use executeOnExecutor (), then it works fine a second time. But why does the execute () function not work? Is AsyncTask's life related to a fragment or something else?

Thanks in advance!

+6
source share
2 answers

It seems to me that something is hanging in AsyncTask . In modern versions of Android AsyncTask , a single thread runs unless you specify an Executor that is multithreaded. onPreExecute() still succeeds because it works in the main thread. You never see doInBackground second time, although due to the fact that the only background thread is still hanging from the first call. You need to examine the contents of LocalKeekLauncherFragment.setFragment(fragment) to find out what causes the hang.

+1
source

It seems that the doInBackground thread probably crashed a second time. It cannot remain stuck from the first attempt, since onPostExecute is called, and this is only possible if doInBackground successfully returned the value.

0
source

Source: https://habr.com/ru/post/952245/


All Articles