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 executes until onPostExecute(). However if I go to other fragment and opens this fragment newly(by creating a new fragment object and replacing to it) then only onPreExecute() is executed. Why doesn't this asyncTask object get executed well for the second time?
Intestingly if I use executeOnExecutor() then it works fine for the second time. But why doesn't execute() work? Is AsyncTask's life tied to fragment or something?
Thanks in advance!
In summary, the three most common issues with AsyncTask are: Memory leaks. Cancellation of background work. Computational cost.
Use getStatus() to get the status of your AsyncTask . If status is AsyncTask. Status. RUNNING then your task is running.
This class was deprecated in API level 30. AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.
doInBackground(Params) – This method is invoked on the background thread immediately after onPreExecute() finishes its execution. Main purpose of this method is to perform the background operations that can take a long time. The parameters of the Asynchronous task are passed to this step for execution.
It sounds to me like something is hanging in the AsyncTask
. In modern versions of Android AsyncTask
s run on a single thread unless you specify an Executor
that's multi-threaded. onPreExecute()
still runs successfully because that runs on the main thread. You never see doInBackground
the second time though because the single background thread is still hung from the first call. You'll need to examine the contents of LocalKeekLauncherFragment.setFragment(fragment)
to see what's causing the hang.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With