Search code examples
androidimageimageviewhttpurlconnectionpicasso

Android how to make images load from HTTP every few seconds


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);

Solution

  • 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);