7

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);
Abid Khan
  • 2,451
  • 4
  • 22
  • 45

5 Answers5

14

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();
frogatto
  • 28,539
  • 11
  • 83
  • 129
  • I am using ArrayList to get Images urls from server then using an object to access urls. Now the problem is how to alter these urls time by time and to pass them in to `downloader` method that downloads an Image and sets as background of the view that was pass to it. Show me how to use the thread in that way. – Abid Khan Apr 08 '14 at 06:26
  • Let me check it and will tell you back – Abid Khan Apr 08 '14 at 06:36
  • here in this line `downloader.download(item.imageurl(), bgImage);` `item.imageurl()` is a string how can I pas index values one by one at a time? – Abid Khan Apr 08 '14 at 06:45
  • 1
    thanks a lot you helped me by sparing too much time on my problem. – Abid Khan Apr 08 '14 at 06:53
4

Set up your ImageView like this:

  <ImageView
        android:id="@+id/imgBackground"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:adjustViewBounds="true"
        android:contentDescription="@string/app_name"
        android:scaleType="fitXY" />

You can Use TimerTask to achieve this.

// Declaration and Initialization :

List<String> mImageUrl = new ArrayList<String>();
private ImageLoader mImageLoader =  new ImageLoader(MainActivity.this);
Timer timer = new Timer(); // changed
int i = 0;

// Put this code in your onCreate :

timer.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                if (i < mImageUrl.size()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            mImageLoader.DisplayImage(mImageUrl.get(i), img);
                            i++;
                        }
                    });
                } else {
                    i = 0;
                }
            }
        }, 0, 2000);

The timer task will start in 0 seconds and it will change the background every 2 seconds. You can change this as like as you want. Its working fine. I have tested.

You can read more about the timertask here.

You can also cancel the timer with the help of timer.cancel() HIH.

Rajesh Satvara
  • 3,842
  • 2
  • 30
  • 50
Rethinavel
  • 3,912
  • 7
  • 28
  • 49
1
    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++)
             {
 runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                                       item = list.get(i);

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

                        }
                    });
             }
Jogendra Gouda
  • 405
  • 4
  • 17
0

Try this way hope this will help you for more improvement of your code...

  1. you need "Aquery(AndroidQuery)" jar from this reference : https://code.google.com/p/android-query/downloads/detail?name=android-query-full.0.24.3.jar

2.now add this jar on your project lib folder and add to build path or as library.

3.now it's time for code using "Aquery(AndroidQuery)" to download images from server(here is my demo code you can modified as per your requirement).

"activity_main.xml"

       <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
           <ImageView
            android:id="@+id/imgFromServer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"/>
           <ProgressBar
            android:id="@+id/pbrImageLoader"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"/>
         </FrameLayout>
    </LinearLayout>

"MyActivity.java" public class MyActivity extends Activity{

    private ImageView imgFromServer;
    private ProgressBar pbrImageLoader;
    private AQuery aQuery;
    private int currentIndex;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imgFromServer = (ImageView) findViewById(R.id.imgFromServer);
        pbrImageLoader = (ProgressBar) findViewById(R.id.pbrImageLoader);
        aQuery = new AQuery(this);
        currentIndex=0;
        final ArrayList<String> imageUrlListFromServer = new ArrayList<String>();
        imageUrlListFromServer.add("http://www.mayoff.com/5-01cablecarDCP01934.jpg");
        imageUrlListFromServer.add("http://www.allindiaflorist.com/imgs/arrangemen4.jpg");
        imageUrlListFromServer.add("http://www.hdwallshub.com/files/submissions/cookie_monster_hd_wallpaper_1405239014.jpg");
        imageUrlListFromServer.add("http://images4.fanpop.com/image/photos/17200000/Tangled-offical-wallpapers-tangled-17286338-1680-1050.jpg");
        imageUrlListFromServer.add("http://wakpaper.com/large/Moons_wallpapers_4.jpg");

        final Timer timer = new Timer();
        downloadImagesFromServer(imageUrlListFromServer, 0, new ImageDownloadedListener() {
            @Override
            public void onDownloadFinish() {
                timer.scheduleAtFixedRate(new TimerTask() {
                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                imgFromServer.setImageBitmap(aQuery.getCachedImage(imageUrlListFromServer.get(currentIndex)));
                               if(currentIndex == imageUrlListFromServer.size()-1){
                                   currentIndex=0;
                               }else{
                                   currentIndex++;
                               }
                            }
                        });
                    }
                },0,2000);
            }
        });



    }

    private void downloadImagesFromServer(final ArrayList<String> imageUrlList,final int index,final ImageDownloadedListener listener){

        aQuery.progress(pbrImageLoader).ajax(imageUrlList.get(index), Bitmap.class, 0, new AjaxCallback<Bitmap>() {
            @Override
            public void callback(String url, Bitmap object, AjaxStatus status) {
                super.callback(url, object, status);
                if ((imageUrlList.size() - 1) == index) {
                    listener.onDownloadFinish();
                } else {
                    downloadImagesFromServer(imageUrlList, index + 1, listener);
                }
            }
        });

    }

    interface ImageDownloadedListener{
        public void onDownloadFinish();
    }


}

Note : "Aquery(AndroidQuery)" also cache images on local so it not get same images from  server if it already downloaded.
Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67
0

try this code.the images was saved in drawable. please do insert a imageview in xml code. noted that the time interval for the following code is 1 sec.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
public ImageView iv;
public static Integer[] mThumbIds = {
    R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4};
int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.imageView);
i=0;
t.start();
}
Thread t = new Thread() {
@Override
public void run() {
    try {
        while (!isInterrupted()) {
            Thread.sleep(1000);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    iv.setImageResource(mThumbIds[i]);
                    i++;
                    if(i >= mThumbIds.length){
                        i = 0;
                    }}});}} 
    catch (InterruptedException e) {
    }}};

}
Alan
  • 1