Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run the same asynctask more than once?

Tags:

android

I have my asyncTask run when the activity first starts, then if network connectivity is not available then i have a refresh button that tries to run the asyncTask to try again. But i get a debug error saying this..

07-29 18:14:21.290: ERROR/AndroidRuntime(9080): FATAL EXCEPTION: main 07-29 18:14:21.290: ERROR/AndroidRuntime(9080): java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once)    07-29 18:14:21.290: ERROR/AndroidRuntime(9080):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:541)    07-29 18:14:21.290: ERROR/AndroidRuntime(9080):     at android.os.AsyncTask.execute(AsyncTask.java:499)   07-29 18:14:21.290: ERROR/AndroidRuntime(9080):     at com.fttech.gameIT.MainMenu$1.onClick(MainMenu.java:90) 

Is there anyway to run this twice?

like image 498
coder_For_Life22 Avatar asked Jul 29 '11 22:07

coder_For_Life22


People also ask

How many times an instance of AsyncTask can be executed?

AsyncTask instances can only be used one time.

Can we run multiple async task at a time?

There is a limit of how many tasks can be run simultaneously. Since AsyncTask uses a thread pool executor with limited max number of worker threads (128) and the delayed tasks queue has fixed size 10, if you try to execute more than 138 your custom tasks the app will crash with java.

What happens to AsyncTask if activity is destroyed?

If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It will go on living until it completes. And when it completes, the AsyncTask won't update the UI of the new Activity.

What is the replacement of AsyncTask?

Alternative 1: Using Executor and Handler The executor will help in performing any task in the background and the handler will help to make UI changes.


2 Answers

Just create another instance and execute it.

like image 59
Cristian Avatar answered Oct 24 '22 09:10

Cristian


Just like threads, AsyncTasks can't be reused. You have to create a new instance every time you want to run one.

like image 34
Ragunath Jawahar Avatar answered Oct 24 '22 09:10

Ragunath Jawahar