I'm new here and noob as well. I started learning Java and Android by making my first simple app.
I want to do the time loop to do some function every 1 sec.
I have this:
new Timer().scheduleAtFixedRate(new TimerTask(){
@Override
public void run(){
imV.setImageResource(stageArray.getResourceId(step, -1));
Log.d("MyApp","I am here");
step ++;
}
},0,1000);
It's in my init()
function.
After I run this on my device, the app crashes.
When I delete the imV.setImageRes...
line it runs, but I don't get log notifications.
The step value is changing.
Something similiar is happening when I use a Handler.
So why my app crash?
Why cannot I see any log.d from this loop?
Are there better ways to do time loop to make simple changes?
Your app has crashed because you access the Android UI toolkit from outside the UI thread when you call imV.setImageResource(stageArray.getResourceId(step, -1)); . So that, exception has occurred. You must set image for imageview in UI thread:
runOnUiThread(new Runnable() {
@Override
public void run() {
imV.setImageResource(stageArray.getResourceId(step, -1));
}
});
Or simple solution with CountDownTimer
new CountDownTimer(totalStep * 1000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
step = millisUntilFinished/1000;
imV.setImageResource(_yourResID);
}
@Override
public void onFinish() {
Log.d("Finish", "Done");
}
}.start();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.