1

I am trying to make a slideshow of a few images while making an android app. I am using this code below

final int[] array = {R.drawable.cow_1, R.drawable.cow_2, R.drawable.cow_3, R.drawable.cow_4};
for (int i = 0; i < 4; i++){
    final int finalI = i;
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {                                          
            animal_image.setImageResource(array[finalI]);
        }
    }, 4000);
}

The problem I am facing is that I am not getting the slideshow of images one-by-one instead the code is showing the last image after the first one directly. There's some problem with the code, please help me fix it.

2 Answers2

1

Try with below

final int[] array = {R.drawable.cow_1, R.drawable.cow_2, R.drawable.cow_3, R.drawable.cow_4};
for (int i = 0; i < 4; i++){
    final int finalI = i;
    Thread.sleep(4000);
     animal_image.setImageResource(array[finalI]);
}

you have to add try{... }catch(Exception e){} block.

Mehul Kabaria
  • 6,404
  • 4
  • 25
  • 50
  • Hello! I have tried with this code and Logcat is showing that the app is skipping frames. Maybe this is taking a lot of memory. – Rahul Siyanwal Mar 27 '19 at 17:45
0

What you code is doing is that it is creating a Handler for each of the image and setting the delay to 4 seconds. The for loop will run instantly for each iteration and all the Handlers that have been created will run after 4 seconds. This causes the last image to show up because the last Handler will have run a few milliseconds after the rest. In order to fix this, you need to have an incremental timer for each Handler.

final int[] array = {R.drawable.cow_1, R.drawable.cow_2, R.drawable.cow_3, R.drawable.cow_4};
for (int i = 0; i < 4; i++){
    final int finalI = i;
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {                                          
            animal_image.setImageResource(array[finalI]);
        }
    }, 4000 * finalI);
}

Using the above given code, the first image will be displayed, and all the other images will be displayed after a multiple of 4 seconds based on the image number (image 2 will be shown after 4 seconds, image 3 will be shown after 8 seconds, image 4 will be shown after 12 seconds and so on).

Bilal Naeem
  • 962
  • 7
  • 13