I am new to programming and I have struggled with this for days and cannot get it to work.
I have a loop to execute some tasks. It will display a picture in an ImageView for that particular task. So it goes something like this:
- setImageResource
- do some task
- wait for 1 second
- then start everything again until the commands end
- when all commands end, close that activity by calling finish()
I tried to use a handler with runnable and asynctask but I cannot get it to work. The UI is always updated later than the 1 second delay. As I call finish() after the commands ends, the photo seems not show up at all.
for(int i=0; i<actions.size(); i++) {
switch((int)actions.get(i)[0]) {
case 0:
ivActionIcon.setImageResource(R.drawable.image);
sleeping=true;
DelayAsyncTask delay=new DelayAsyncTask();
delay.execute();
while(sleeping){};
break;
}
}
finish();
class DelayAsyncTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
try {
Thread.sleep(5000);
} catch(Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
sleeping=false;
}
}
I am using a variable “sleeping” to let the main thread to wait for the delay.
Just from taking a guess this loop is somewhere in a UI thread. That means that you are blocking the UI thread until the async finishes. That is a NO-NO! Why not just update the image in the onPostExecute? Something like
obviously remove this line of code as well (I don’t think I ever know a reason for doing something like that anyway).