Zain Zafar
Zain Zafar

Reputation: 1607

Creating a slidshow in android

I am creating an application in which user can start slideshow (auto-play) of images by clicking a specific button. I have started a thread in which a new image is set to my imageView after a 1 sec. Problem is that my app stop responding and crashes after few seconds.

Please check my code and help me to resolve this issue. (variables are correctly initialized)

 playThread = new Runnable() {

        @Override
        public void run() {
            synchronized (this) {
            for (int i=pos;i<mImageIds.length;i++){
            //pos++;

            selectedImage.setImageResource(mImageIds[i]);

            try {

                wait(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }}
        }};

    play.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            runOnUiThread(playThread);



        }   
    });

}

my logcat while app freezes!

enter image description here

Upvotes: 1

Views: 74

Answers (1)

Deniz
Deniz

Reputation: 459

The runOnUiThread() method is meant to update the user interface. Any other logic shouldn't happen there. So I would suggest something like this:

Thread t = new Thread() {
    for (int i=pos;i<mImageIds.length;i++){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                selectedImage.setImageResource(mImageIds[i]);
        }};);
    try {
        wait(1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}};

play.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        t.start();
    }   
});

Please note, I didn't test this code.

Upvotes: 1

Related Questions