30

I did added async library at my project and checked already, I don't know why code flow doesn't go in to asynctask

Code

public void doMysql()
{
    Log.v("doMysql", "accessed");

    new AsyncTask<Void, Void, String>() {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.e("AsyncTask", "onPreExecute");
        }
        @Override
        protected String doInBackground(Void... params) {
            Log.v("AsyncTask", "doInBackground");

            String msg = "";

            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://172.16.100.172:52273/mysql");

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            nameValuePairs.add(new BasicNameValuePair("myday", Integer.toString(day_picker.getYear()) + 
                    addZero(day_picker.getMonth() + 1) + 
                    addZero(day_picker.getDayOfMonth())));
            nameValuePairs.add(new BasicNameValuePair("mystar", changeStar(day_picker.getMonth() + 1, day_picker.getDayOfMonth())));
            nameValuePairs.add(new BasicNameValuePair("mybt", changeBloodType(blood_picker.getValue())));
            nameValuePairs.add(new BasicNameValuePair("mynum", "" + myPhone.getText()));
            nameValuePairs.add(new BasicNameValuePair("yournum", "" + partnerPhone.getText()));
            nameValuePairs.add(new BasicNameValuePair("myregID", regid));
            try {
                Log.v("setEntity", "before");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                Log.v("setEntity", "after");

            } catch (UnsupportedEncodingException e1) {
                Log.v("UnsupportedEncodingException", "");
                e1.printStackTrace();
            }
            //172.16.101.28
            try {  
                Log.v("post", "before");
                HttpResponse httpresponse = httpclient.execute(httppost);
                Log.v("post", "after");
                Log.v("HttpResponse ",httpresponse.getEntity().toString());
            } catch (ClientProtocolException e) {
                Log.v("ClientProtocolException", "ClientProtocolException");
                e.printStackTrace();
            } catch (IOException e) {
                Log.v("IOException", "IOException");

                e.printStackTrace();
            }

            return msg;
        }
        @Override
        protected void onPostExecute(String msg) {
            Log.v("AsyncTask", "onPostExecute");

        }
    }.execute(null, null, null);
}

I have a log statement in the code 'Log.v("AsyncTask", "doInBackground");'

But it doesn't show up in the logger 'Log.v("AsyncTask", "doInBackground");'

Siddharth
  • 9,349
  • 16
  • 86
  • 148
LKM
  • 2,410
  • 9
  • 28
  • 53
  • try .execute() instead of .execute(null, null, null); – Serhii Nadolynskyi Nov 12 '14 at 15:33
  • 1
    results is same... Why do you think that would be a solution? Locally, it worked very well with '.execute(null,null,null)' – LKM Nov 12 '14 at 15:37
  • 2
    possibly another asynctask is still executing – njzk2 Nov 12 '14 at 15:52
  • `I got a log 'Log.v("AsyncTask", "doInBackground");'` ??? typo? – marcinj Nov 12 '14 at 15:53
  • @njzk2 Really?? It could... but How can I find ?? – LKM Nov 12 '14 at 16:05
  • 1
    @brightstar At my log cat , 'AsyncTask : doInBackground' is marked... – LKM Nov 12 '14 at 16:06
  • 1
    @LKM well, if you have 'doInBackground' in your logcat then your asynctask executes fine – marcinj Nov 12 '14 at 16:08
  • `I got a log 'Log.v("AsyncTask", "doInBackground");' But It doesn't show me that log ' Log.v("AsyncTask", "doInBackground");'` what? – njzk2 Nov 12 '14 at 16:11
  • @LKM to check if your problem is caused by other asynctask blocking yours, you can try executing it in parallel (depends on android version): `.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);`. – marcinj Nov 12 '14 at 16:17
  • My Async Task does not work: this is an exception for only one place: however: when I want to update the screen when the user comes to the last item in my ListView using onScroll Listener. When nothing worked I switched to usual thread for the background operation and handler to update Ui for postExecute. – Abhinav Saxena Apr 08 '15 at 07:12

4 Answers4

77

You should execute your task with executor

task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

Because in lower versions of Android all AsyncTasks were executed at single background thread. So new tasks might be waiting, until other task working.

In lower versions in Android (actually on pre-HONEYCOMB) you can't execute AsyncTask on executor.

Change your code to

public void executeAsyncTask()
{
    AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.e("AsyncTask", "onPreExecute");
        }

        @Override
        protected String doInBackground(Void... params) {
            Log.v("AsyncTask", "doInBackground");
            String msg = null;
            // some calculation logic of msg variable
            return msg;
        }
        @Override
        protected void onPostExecute(String msg) {
            Log.v("AsyncTask", "onPostExecute");
        }
    };

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB/*HONEYCOMB = 11*/) {
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    } else {
        task.execute();
    }
}
Zhar
  • 3,330
  • 2
  • 24
  • 25
Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119
6

I was in the same situation.

  1. I made a call AsyncTask.cancel(boolean mayInterruptIfRunning) passing true
  2. Then I assumed (I was wrong) that the doInBackground() of this task was now interrupted

By adding logs statements I realised that the very first asyncTask was still running ... thus preventing another asyncTask to execute. It's doInBackground() method was running an infinite while loop so I simply had to change condition to consider all the possible "break" cases...

Md. Sabbir Ahmed
  • 850
  • 8
  • 22
A. Masson
  • 2,287
  • 3
  • 30
  • 36
6

Doing this not working for you?

task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

I was already doing this and the problem was still there, the problem was I was using AsyncTask to run long background tasks that do run forever, so the ThreadPoolExecutor's worker threads were already occupied.

In my case AsyncTask.THREAD_POOL_EXECUTOR (use debugger to get your executor properties) was having the ff properties:

maximumPoolSize = 3
largetsPoolSize = 2
corePoolSize =2 

So disabling one of the long running asyncTasks made my doInBackground code to run but that is not the right solution.

The right solution is I moved long running tasks into custom threads rather than using AsyncTask.

dsharew
  • 10,377
  • 6
  • 49
  • 75
  • 1
    Alternatively you can define your own custom executor - it is not so hard, just see how it is done in AsyncTask, and make it with more threads in the pool – Haggai Nov 22 '18 at 09:05
5

Quoting Android Documentation for Async Task

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.

Use this snippet for triggering AsyncTask:

if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
   asyncTaskInstance.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
else
   pdfPageChanger.execute(params);
Jaydev
  • 1,794
  • 20
  • 37