I am trying to execute a task (i.e. load data from a text file) asynchronously and repeatedly at the specified time (i.e. every few seconds, although this speed may change at runtime).
I did some research and decided that this would require either AsyncTask or a separate thread. I decided to use AsyncTask for simplicity.
Now I need to execute this AsyncTask according to the re-timer schedule. I believe I should use Timer and TimerTask.
The code below is a simple form of what I'm trying to achieve. When I try to run this code using the Android emulator (via the Eclipse IDE), I get the following message: "Sorry! The application stopped unexpectedly. Try again."
I would like to know where the problem is and how I can fix it. Thank!
public class Sample extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SimpleTimerTask myTimerTask = new SimpleTimerTask();
long delay = 0;
long period = 5000;
Timer myTimer = new Timer();
myTimer.schedule(myTimerTask, delay, period);
}
private class SimpleAsyncTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
return null;
}
}
private class SimpleTimerTask extends TimerTask {
public void run() {
new SimpleAsyncTask().execute();
}
}
}
EDIT: Here are the LogCat posts that seem relevant
FATAL EXCEPTION: Timer-0
java.lang.ExceptionInInitializerError
at ...
Called: java.lang.RuntimeException: cannot create a handler inside a thread that did not call Looper.prepare ()
at ...
source
share