Abid Khan Abid Khan - 1 month ago 25
Android Question

Android: changing Image with time interval

I am using

ImageDownloader
class to get images from server and getting these images links using an ArrayList. After downloading the Image I am setting the Image as
background
of the layout. All is working but I want to change these Images after a specific
time interval
and set as background different images. I have gone through many posts here but didn't get what I want. As I have all Images links in ArrayList, so how can I set a timer to change the images, coming from that
ArrayList
.It always show me the first Image at
index zero
even I have set a timer but the same Image is showing again? Please help me if someone has any code example and see my code what to change there?

final ImagesSerialized item;
final ImageView bgImage=(ImageView) findViewById(R.id.image);
ArrayList<ImagesSerialized> list;
control = (Controller) getApplicationContext();
list = (ArrayList<ImagesSerialized>) control.Table_Images.GetData();

for(int i=0; i<list.size(); i++)
{
item = list.get(i);
}




downloader = new ImageDownloader();
downloader.download(item.imageurl(), bgImage);

Answer

I do not know about ImageLoader component but scheduling a timer on a view is quite easy in Android.(Without any additional Object)

final ImageView bgImage=(ImageView) findViewById(R.id.image);

...

new Runnable() {
    int updateInterval = 1000; //=one second

    @Override
    public void run() {

        // Any code which goes here will be executed every 'updateInterval'
        // change your background here            

        bgImage.postDelayed(this, updateInterval);
    }
}.run();

You can change this template as you wish, suppose I want to stop this timer, for this purpose I have to add a stop method to my runnable(This stop method acts synchronized and do not cause inconsistency in timer inner codes):

Runnable myRunnable = new Runnable() {
    int updateInterval = 1000; //=one second
    boolean stop = false;

    public void stop() {
        this.stop = true;
    }    

    @Override
    public void run() {

        // Any code which goes here will be executed every 'updateInterval'
        // change your background here            

        if(!stop) {
            bgImage.postDelayed(this, updateInterval);
        }
    }
}.run();

Now I can stop it by myRunnable.stop();

EDIT : You should iterate your array of URLs and pass one of them to your downloader. It can be accomplished by this snippet code:

int arraySize = list.size();

new Runnable() {
    int currentIndex = 0;
    int updateInterval = 1000; //=one second

    @Override
    public void run() {

        currentIndex += 1;
        if(currentIndex == arraySize){
            currentIndex = 0;
        }

        item = list.get(currentIndex);       
        downloader.download(item.imageurl(), bgImage);            

        bgImage.postDelayed(this, updateInterval);
    }
}.run();