DoInBackground runs so fast when using AsyncTask in fragment

I have such a strange problem when using Asynctask in fragment ,

In onCreate of fragment I called Asynctask following:

 @Override public void onCreate(Bundle savedInstanceState) { // Step 1 new FitnessHistoryDataAsync(getActivity()).execute(10); super.onCreate(savedInstanceState); } 

and doInBackground :

 @Override protected Boolean doInBackground(Integer... params) { // Step 2 Log.i("", "doInBackground"); Constants.SDK.getFitnessHistoryData(context, 10, new FitnessHistoryListener() { @Override public void onReceiveFailed(String errorMessage) { // Step 4 Log.i("", "error " + errorMessage); } @Override public void onReceiveData( FitnessHistory[] fitnessHistoryData) { // Step 4 Log.i("", "onReceiveData"); } }); return true; } 

and onPostExecute :

 @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); // Step 3 Log.i("", "onPostExecute"); // Hide progress bar dialog Constants.connectivity.hideProgressDialog(); } 

My Asynctask executed as follows: Step 1 , Step 2 , Step 3 , then Step 4 .

The problem is the doInBackground method, where Step 2 and Step 4 cannot work simultaneously until Step 3 run in the onPostExecute method.

I want everything in the doInBackground method doInBackground start before going to the onPostExecute method.

Please help me.

Thanks.

EDIT:

I switched to the following code:

 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Step 1 new FitnessHistoryDataAsync(getActivity()).executeonExecutor(AsyncTask.THREAD_POOL_EXECUTOR, 10); } 

Although I used AsyncTask.THREAD_POOL_EXECUTOR or AsyncTask.SERIAL_EXECUTOR to try to fix this problem, but I can not.

0
source share
2 answers

It looks like the library I used is also a different thread. So, I do not need to create a new AsyncTask thread.

Just edit the encoding as follows:

 Constants.SDK.getFitnessHistoryData(context, 10, new FitnessHistoryListener() { @Override public void onReceiveFailed(String errorMessage) { // Step 4 Log.i("", "error " + errorMessage); } @Override public void onReceiveData( FitnessHistory[] fitnessHistoryData) { // Step 4 Log.i("", "onReceiveData"); // TODO Directly updated UI in here when already received new data } }); 

This solved my problem.

0
source

Call new FitnessHistoryDataAsync(getActivity()).execute(10); before super.onCreate(savedInstanceState); - The problem that you must fix first.
Changing this to something like this

 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Step 1 new FitnessHistoryDataAsync(getActivity()).execute(10); } 
+3
source

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


All Articles