I'm performing a Database operation in the doInBackground
method inside an AsyncTask
on Android
.
For some reason, the UI
get blocked during the 5-6 seconds that the operation takes.
It does not make any sense for me, the operacion inside the doInBackground
should not be executed in the UI Thread
, right?
Here is my code:
private class CountItems extends AsyncTask<String, Void, Integer> {
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(context);
dialog.setCancelable(false);
dialog.setMessage(getString(R.string.asynTask_loading));
dialog.show();
}
@Override
protected Integer doInBackground(String... params) {
// This operation takes 5-6 seconds.
return app.databaseSession().getMyObjectDao().count(selectedProject, filter, null, false);
}
@Override
protected void onPostExecute(Integer result) {
counterTextView.setText(String.valueOf(result));
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
I've made a test. If I put a Thread.sleep()
inside the doInBackground
method, it is executed in a different Thread
without blocking the UI
.
Like this:
@Override
protected Integer doInBackground(String... params) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 0;
}
Any ideas? Thanks in advance.