Friday, 17 August 2012

Image Slide Show

Hi everyone.
In this tutorial i am going to show you all the code which when run will display the images as a slideshow.
Below is the attached screen shot : 



For this i am considering the images from the Sdcard's images folder where i am having all the images.
Next to display the images i am using View Flipper concept. I am adding ImageViews to the viewflipper so that the images can be displayed onto the screen.
Now lets start 
Design an xml layout as below (say main.xml)



  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.     xmlns:tools="http://schemas.android.com/tools"
  3.     android:layout_width="match_parent"
  4.     android:layout_height="match_parent" >

  5.     <ViewFlipper
  6.         android:id="@+id/main_flipper"
  7.         android:layout_width="wrap_content"
  8.         android:layout_height="wrap_content"
  9.         android:layout_alignParentLeft="true"
  10.         android:layout_alignParentTop="true" >
  11.     </ViewFlipper>

  12. </RelativeLayout>
Now place few images into the sdcard's images folder.
We can get the path of the images folder of our sdcard using the following statement.

File sdcardPath = new File(Environment.getExternalStorageDirectory()
.getPath() + "/images");
String sdcard =  sdcardPath .getPath();

Now let us create a method named  to setImagesToFlipper() add ImageViews dynamically to the ViewFlipper.
I am creating imageviews dynamically because the number of images in the sdcard may not be the same all the times.
Consider the following function.

  1. private void setImagesToFlipper(ViewFlipper flipper, File sdcardPath) {
  2. int imageCount = sdcardPath.listFiles().length;
  3. for (int count = 0; count < imageCount - 1; count++) {
  4. ImageView imageView = new ImageView(this);
  5. Bitmap bmp = BitmapFactory.decodeFile(sdcardPath.listFiles()[count]
  6. .getAbsolutePath());
  7. imageView.setImageBitmap(bmp);
  8. flipper.addView(imageView);

  9. }

  10. }
In the above code 

Line 2 : imageCount will hold the number of files in the path (here images folder).
Line 4 : Dynamically creating an imageView.
Line 5 : Getting a bitmap object of the image present in the sdcard/images folder.
Line 7 : Setting the bitmap image to the image view 
Line 8 : Adding the image to the ViewFlipper.

Now we are with all the images of the sdcard/images folder. Now we need to give a slide show for the images.The following code helps to do this.

  1.             runnable = new Runnable() {
  2. public void run() {
  3. handler.postDelayed(runnable, 3000);
  4. imageViewFlipper.showNext();

  5. }
  6. };
  7. handler = new Handler();
  8. handler.postDelayed(runnable, 500);
If you want to update the UI in the middle of a thread execution, the best approach to do this is creating a handler which will update the UI and let the thread to continue running.
That's the reason i used a handler here.
The line 4 makes the images to slide.showNext() of the ViewFlipper manullay shows the next Child i.e.., the next image .

Now lets have a look at the entire code 

  1.   public class MainActivity extends Activity {

  2. ViewFlipper imageViewFlipper;
  3.         Handler handler;
  4. Runnable runnable;

  5. @Override
  6. public void onCreate(Bundle savedInstanceState) {
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.main);
  9. imageViewFlipper = (ViewFlipper) findViewById(R.id.main_flipper);

  10. // getting the path of the images folder in the sdcard
  11. File sdcardPath = new File(Environment.getExternalStorageDirectory()
  12. .getPath() + "/images");

  13. setImagesToFlipper(imageViewFlipper, sdcardPath);

  14. runnable = new Runnable() {

  15. public void run() {

  16. handler.postDelayed(runnable, 3000);
  17. imageViewFlipper.showNext();

  18. }
  19. };
  20. handler = new Handler();
  21. handler.postDelayed(runnable, 500);

  22. }
  23.      /**
  24.        * Sets the images to the ViewFlipper
  25.        * @param flipper : the Flipper object
  26.        * @param sdcardPath : the image file in the sdcard
  27.      */
  28.      private void setImagesToFlipper(ViewFlipper flipper, File sdcardPath) {
  29. int imageCount = sdcardPath.listFiles().length;
  30. for (int count = 0; count < imageCount - 1; count++) {
  31. ImageView imageView = new ImageView(this);
  32. Bitmap bmp = BitmapFactory.decodeFile(sdcardPath.listFiles()[count]
  33. .getAbsolutePath());
  34. imageView.setImageBitmap(bmp);
  35. flipper.addView(imageView);

  36. }

  37. }
  38. }



Any suggestions are welcomed.



Please comment if anyone has some or the other problem with this one.











13 comments:

  1. here is my logcat


    08-17 14:31:48.018: I/Process(13058): Sending signal. PID: 13058 SIG: 9
    08-17 14:32:55.080: D/szipinf(13271): Initializing inflate state
    08-17 14:35:18.994: D/szipinf(13462): Initializing inflate state
    08-17 14:35:39.736: D/szipinf(13495): Initializing inflate state
    08-17 14:35:39.783: D/dalvikvm(13495): GC_EXTERNAL_ALLOC freed 45K, 51% free 2687K/5379K, external 0K/0K, paused 34ms
    08-17 14:35:39.791: D/AndroidRuntime(13495): Shutting down VM
    08-17 14:35:39.791: W/dalvikvm(13495): threadid=1: thread exiting with uncaught exception (group=0x40015560)
    08-17 14:35:39.791: E/AndroidRuntime(13495): FATAL EXCEPTION: main
    08-17 14:35:39.791: E/AndroidRuntime(13495): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.slideshow1/com.example.slideshow1.MainActivity}: java.lang.NullPointerException
    08-17 14:35:39.791: E/AndroidRuntime(13495): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1768)
    08-17 14:35:39.791: E/AndroidRuntime(13495): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784)
    08-17 14:35:39.791: E/AndroidRuntime(13495): at android.app.ActivityThread.access$1500(ActivityThread.java:123)
    08-17 14:35:39.791: E/AndroidRuntime(13495): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939)
    08-17 14:35:39.791: E/AndroidRuntime(13495): at android.os.Handler.dispatchMessage(Handler.java:99)
    08-17 14:35:39.791: E/AndroidRuntime(13495): at android.os.Looper.loop(Looper.java:130)
    08-17 14:35:39.791: E/AndroidRuntime(13495): at android.app.ActivityThread.main(ActivityThread.java:3835)
    08-17 14:35:39.791: E/AndroidRuntime(13495): at java.lang.reflect.Method.invokeNative(Native Method)
    08-17 14:35:39.791: E/AndroidRuntime(13495): at java.lang.reflect.Method.invoke(Method.java:507)
    08-17 14:35:39.791: E/AndroidRuntime(13495): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
    08-17 14:35:39.791: E/AndroidRuntime(13495): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
    08-17 14:35:39.791: E/AndroidRuntime(13495): at dalvik.system.NativeStart.main(Native Method)
    08-17 14:35:39.791: E/AndroidRuntime(13495): Caused by: java.lang.NullPointerException
    08-17 14:35:39.791: E/AndroidRuntime(13495): at com.example.slideshow1.MainActivity.setImagesToFlipper(MainActivity.java:55)
    08-17 14:35:39.791: E/AndroidRuntime(13495): at com.example.slideshow1.MainActivity.onCreate(MainActivity.java:34)
    08-17 14:35:39.791: E/AndroidRuntime(13495): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    08-17 14:35:39.791: E/AndroidRuntime(13495): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722)
    08-17 14:35:39.791: E/AndroidRuntime(13495): ... 11 more
    08-17 14:35:42.455: I/Process(13495): Sending signal. PID: 13495 SIG: 9

    ReplyDelete
  2. You need to have a folder named images in the sdcard with images (only images) to work this.
    Or else change the name of the folder named "images" in the line File sdcardPath = new File(Environment.getExternalStorageDirectory()
    .getPath() + "/images"); with the folder of images that you have.

    ReplyDelete
  3. Or replace the lines
    setImagesToFlipper(imageViewFlipper, sdcardPath);

    runnable = new Runnable() {

    public void run() {

    handler.postDelayed(runnable, 3000);
    imageViewFlipper.showNext();

    }
    };
    handler = new Handler();
    handler.postDelayed(runnable, 500);

    }

    with

    if (sdcardPath.exists()) {
    setImagesToFlipper(imageViewFlipper, sdcardPath);

    runnable = new Runnable() {

    public void run() {

    handler.postDelayed(runnable, 3000);
    imageViewFlipper.showNext();

    }
    };
    handler = new Handler();
    handler.postDelayed(runnable, 500);

    }
    else
    Toast.makeText(this, "No folder with name images..", Toast.LENGTH_LONG).show();
    }

    ReplyDelete
  4. hi
    i tried it and it works too. the only problem is that when i try to rotate my phone to landscape view it crashes any solution.

    ReplyDelete
    Replies
    1. hi one more thing when i updated my sd card folder by putting some more images. it crashes.

      Delete
    2. why dont you create another layout-land folder with the same xml file as in the layout folder. This will be used as the layout when the mobile is in the landscape mode. And to prevent crashing try to use

      System.gc();
      in the ondestroy()

      Delete
    3. And i did get any problem when updating my sdcard folder's images

      Delete
  5. ImageView imageView=ImageView(this); and flipper.addView(imageview); error please help me

    ReplyDelete
    Replies
    1. are you still seeing the issue senthil?

      Delete
  6. Hello sharath g.
    I am using these code but i have an one problem.It shows slideshow of images but only upto 3 images, after those images are added not to show that images. can u plz help me on these condition......

    private void setImagesToFlipper(ViewFlipper flipper, File sdcardPath) {
    int imageCount = sdcardPath.listFiles().length;
    for (int count = 0; count < imageCount - 1; count++) {
    ImageView imageView = new ImageView(this);
    Bitmap bmp = BitmapFactory.decodeFile(sdcardPath.listFiles()[count]
    .getAbsolutePath());
    imageView.setImageBitmap(bmp);
    flipper.addView(imageView);
    ------------------------------------------------------------------------------------------------------------------

    ReplyDelete
    Replies
    1. Minaj,
      Sorry for the delay. Thought I would get mails for every comment. But that dint happen.
      Can I know exactly what you are looking for? Sorry for this. I didnt get your question.

      Delete
  7. i need help to code for dynamic image slide show ...

    ReplyDelete
    Replies
    1. dynamic image display?

      If that is from a service, one of my suggestion in my mind currently is... get all the image urls, make a call to each url and convert the image from to bitmap and add it to imageview.

      Converting an image from url to a bitmap can be done using following code
      URL url = new URL(imageURL);
      HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
      httpConnection.setDoInput(true);
      httpConnection.connect();
      InputStream inputStream = httpConnection.getInputStream();
      Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);

      Delete