-1

My images is loaded from HttpURLConnection.

I have 3 images and want to change them every 2 seconds in one ImageView.

For example, image1 -> image2 -> image3 -> image1 -> image2 ...

Current, my code is as below:

Picasso.with(this).load(BASE_URL + "admin/"+image1).fit().centerInside().into(ivImage);


Picasso.with(this).load(BASE_URL + "admin/"+image2).fit().centerInside().into(ivImage);


Picasso.with(this).load(BASE_URL + "admin/"+image3).fit().centerInside().into(ivImage);
Wei Hang Tan
  • 15
  • 1
  • 7
  • Possible duplicate of [How to repeat a task after a fixed amount of time in android?](https://stackoverflow.com/questions/18353689/how-to-repeat-a-task-after-a-fixed-amount-of-time-in-android) – ADM Mar 23 '19 at 06:31
  • `handle.postDelayed()` might help you.. Beware of the memory leaks though – Nilesh Deokar Mar 23 '19 at 06:31
  • @ADM After I followed the solution, my app crashed. I put Picasso.with(this).load(BASE_URL + "admin/"+image1).fit().centerInside().into(ivImage); inside the run() method. – Wei Hang Tan Mar 23 '19 at 06:49

1 Answers1

0

Use the following method...

private void repeatTask(int counter) {
        switch (counter) {
            case 0:
                Picasso.with(this).load(BASE_URL + "admin/"+image1).fit().centerInside().into(ivImage);
                break;
            case 1:
                Picasso.with(this).load(BASE_URL + "admin/"+image2).fit().centerInside().into(ivImage);
                break;
            case 2:
                Picasso.with(this).load(BASE_URL + "admin/"+image3).fit().centerInside().into(ivImage);
                break;
            default:
                //not possible
                break;
        }
        final int newCounter = counter + 1;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                repeatTask(newCounter == 3 ? 0 : newCounter);
            }
        }, 2000);
    }

This will continue to change your image every 2 sec. Call this method like this in your onCreate() method to start the task...

    repeatTask(0);
Sayan Mukherjee
  • 352
  • 2
  • 21