Android Image Slideshow using ViewPager

Screen slides are transitions between one entire screen to another and are common with UIs like setup wizards or slideshows. This Android tutorial shows how to create image slideshow with ViewPager (provided as part of Android support library). ViewPager can animate screen slides automatically.

Here’s what a screen slide looks like – transition from one screen to the next:

Project Description:

In this Android Image Slideshow tutorial we will be doing the following,

  • Create an image slideshow along with image description using ViewPager and display circle indicator to show the current position in the slideshow.
  • Enclose ViewPager and circle indicator in a layout and provide a border.
  • Retrieve and parse JSON (product information) from remote server and store it as list of products.
  • Handle ViewPager item clicks to display product details in another fragment (ProductDetailFragment)
  • Proper back navigation of fragments on back key pressed.
  • Handle fragment orientation changes and retain the state of the fragment.

We will also be using the following library projects,

Prerequisites

  • Place the Universal Image Loader JAR file in your libs folder and add it to project’s “Build Path”.

Create JSON File

Create a new JSON file and name it as products.json and copy-paste the following content. Place this file in a remote server, for example Apache server’s “www” folder or /webapps/ROOT folder.

Android Project

Create a new Android project and name it as AndroidImageSlideShow .

Download “Android Image Slideshow using ViewPager” ImageViewSlideshow.zip – Downloaded 23708 times – 2 MB

Resources

colors.xml

Create a new file res/values/colors.xml and copy paste the following content.

strings.xml

Open res/values/strings.xml and edit to have the content as shown below.

indicator_tags.xml

Create a new file res/values/indicator_tags.xml and copy the following content. The attributes defined here are used by circle page indicator. You can use this file to change the circle indicator fill color, stroke color, stroke width, circle radius and any other related styles.

img_border.xml

Create a new file res/drawable/img_border.xml and copy the following content. This brings a border to ViewPager and circle page indicator layout.

Layout files

activity_main.xml

This is the main layout file which uses a Framelayout to hold fragments. Open res/layout/activity_main.xml and edit to have the content as shown below.

fragment_home.xml

This layout file is used by HomeFragment to display image slide show using ViewPager. Here it encloses ViewPager and circle page indicator in a single layout by displaying circle page indicator over ViewPager.

vp_image.xml

This layout file is for the content of a fragment to be used by ViewPager. The file contains an image view.

fragmet_pdt_detail.xml

This layout file is used by ProductDetailFragment to display product details when a page (fragment) in ViewPager is clicked.

Sources

TagName

In src folder, create a new class TagName in the package com.androidopentutorials.imageslideshow.utils . This class defines tag and key names defined in JSON.

CheckNetworkConnection

In src folder, create a new class CheckNetworkConnection in the package com.androidopentutorials.imageslideshow.utils .

Before our app attempts to connect to the network, it should check to see whether a network connection is available using getActiveNetworkInfo() and isConnected(). Remember, the device may be out of range of a network, or the user may have disabled both Wi-Fi and mobile data access.

We use this class to check whether the device has internet connection before sending request to receive remote JSON.

PageIndicator

In src folder, create a new interface PageIndicator in the package com.androidopentutorials.imageslideshow.utils . This is a class from Android ViewPagerIndicator library which is used to draw a circle indicator over the ViewPager. This interface is responsible for showing an visual indicator indicating the currently visible view.

CirclePageIndicator

In src folder, create a new class CirclePageIndicator in the package com.androidopentutorials.imageslideshow.utils . This is also a class from Android ViewPagerIndicator library which implements the above interface.

FileUtils

In src folder, create a new class FileUtils in the package com.androidopentutorials.imageslideshow.utils . This class has utility methods to close Reader, Writer, InputStream and OutputStream which is used by JSONParser class.

GetJSONObject

In src folder, create a new class GetJSONObject in the package com.androidopentutorials.imageslideshow.json . For the given URL, it gets JSONObject. It checks for Android version, if it is greater than FROYO then it uses HttpURLConnection else uses HttpClient. For more information on this refer Android Http Clients .

JSONParser

In src folder, create a new class JSONParser in the package com.androidopentutorials.imageslideshow.json . This class opens a connection to the remote json url, creates a reader object, retrieves the json string and returns a JSONObject.

JsonReader

In src folder, create a new class JsonReader in the package com.androidopentutorials.imageslideshow.json . This class has an utility method which takes JSONObject as parameter, parses it and returns a list of products.

Product

In src folder, create a new class Product in the package com.androidopentutorials.imageslideshow.bean . This is a bean class which represents a single product.

ImageSlideAdapter

In src folder, create a new class ImageSlideAdapter in the package com.androidopentutorials.imageslideshow.adapter .

  • This class is an implementation of PagerAdapter to populate pages inside a ViewPager.
  • When you implement a PagerAdapter, you must override the following methods at minimum:
    • instantiateItem(ViewGroup, int)
    • destroyItem(ViewGroup, int, Object)
    • getCount()
    • isViewFromObject(View, Object)
  • When the ImageView is clicked, it starts a FragmentTransaction and replaces the content frame with ProductDetailFragment.

HomeFragment

In src folder, create a new class HomeFragment in the package com.androidopentutorials.imageslideshow.fragment .

  • ViewPager.setCurrentItem() is used to animate screen slides automatically.
  • We use Handler to make ViewPager auto slide after five (5) seconds.
  • If the user slides the screen then we make ViewPager auto slide after ten (10) seconds.

Steps:

  • In onResume(), if there are no products (==null) it sends a request where it executes a background AsyncTask to read remote JSON. It parses this JSON using the JsonReader.getHome() and returns list of products. In onPostExecute() it create ImageSlideAdapter and sets it in ViewPager.
  • For ViewPager, we set touch listener and for MotionEvent.ACTION_UP (which is executed on ViewPager touch release) we post a runnable to the handler queue to be executed after ten (10) seconds which changes teh slide to next image.
  • We also set a page change listener which changes the image name to reflect the current image view.

ProductDetailFragment

In src folder, create a new class ProductDetailFragment in the package com.androidopentutorials.imageslideshow.fragment . This class gets a single product from bundle and displays product image, id and name.

MainActivity

In src folder, create a new class MainActivity in the package com.androidopentutorials.imageslideshow .

  • This is the main activity class.
  • When the app starts, it begins a new FragmentTransaction and starts HomeFragment.
  • It handles proper back navigation of fragments on back key pressed by overriding onBackPressed() .
  • It handles fragment orientation changes and retains the fragment state by overriding onSaveInstanceState() .

AppData

In src folder, create a new class AppData in the package com.androidopentutorials.imageslideshow .

Universal ImageLoader configuration (ImageLoaderConfiguration) is global for application hence create a class which extends android.app.Application and create a global configuration and initialize ImageLoader.

AndroidManifest.xml

Define the activity in AndroidManifest.xml file. To access internet from Android application set the android.permission.INTERNET permission in manifest file as shown below. In <application> element specify android:name by providing the fully qualified name of Application subclass ( AppData ). When the application process is started, this class is instantiated before any of the application’s components.

Output

HomeFragment

1.android-image-slideshow-using-viewpager

ProductDetailFragment

2.android-image-slideshow-using-viewpager-page-detail

  • Pingback: Android Image Gallery using ViewPager » the Open Tutorials

  • Ketan Sharma

    Can you post the source code of this project?

    • The Open Tutorials

      try the download link provided in the article. If it is not working clear browser cache and try again.

      • Guest

        I cant find the link either.

        • AnotherGuest

          at part 4 “Android Project” in this page, there is a big blue button for downloading

  • MERT

    sorry I can not connect. I’m installing json file to dropbox does not happen again, what’s the problem?

    ( https://www.dropbox.com/s/zhdokf46jxxe6ma/products.jso ) connection address this.

  • guest

    how to display this in Fragment

    please tell me
    your help will be appreciated

  • C.e. Abdullah Faroun

    thank you for the nice app :D

  • ashwin

    i cant see any images ..its blank.. looks like the images are not getting downloaded… any fix?

    • Saman Sajedi

      I think that’s because of products.json
      1. upload 5 photos
      2. replace their direct link with the links in .json file
      3. upload your .json file
      4. and put your .json’s direct link in String url which is in HomeFragment class
      that should fix it

      • reenath reddy

        Where should i upload these images?? and laso what’s the difference between images that are already there and that am gonna be uploading??

        • Saman Sajedi

          you can use this the links of images in this tutorial. I uploaded them to use my own images. idk, just build your .json and the problem’s gonna be solved :D

  • Laxman Singh

    its very nice tutorial what exactly i need. but only thing i need that how to create product.json file of database??

  • Alex Gonzalez

    Nice Tutorial & code, but, How can I link the URL’s As Constants and do an Infinite ListView?

  • Boke Ka Lay

    This is exactly what I want but there are no images coming out. Is there a solution to solve this?

  • Armando Marques Sobrinho

    Good tutorial, I got the source code and try to compile it in the “IntelliJIdea 14″ and after a monster job to importe the project, I got it work, but, only appear in the screen of the device a square with borders and a grey bar above, debugging the app I see with the call to these line “JSONObject jsonObject = getJsonObject(urls[0]);” return null because the json motor.
    the “urls[0]” in this case I got it from “String url = “http://127.0.0.1:8080/products.json”;” which is im my “www” configured by the apache server in my machine.

    I need to do any more configuration to force the app got the images returned by and for the json motor?

    if someone know, tell-me, please!

    thank’s!

    peace!

    • saur

      ok the solution is to check the Json file, in my case i forgot “{” while copying, always validate json online.

  • joel lazo

    Where is the ‘urls’ address variable defined ?

  • Pingback: Fragments not loading in my project | 我爱源码网

  • keyrune sasuke

    Nice tutorial. Manage to get it work just fine. Now I need that image to be zoom, pinch to zoom etc. Any tips? Thanks.

    • Rushabh Shah

      use zoomviewers control

  • keyrune sasuke

    How to prevent the app from closing when there is no internet connection? Previously while working with json I use this add this code in json to make it work while no internet connection. How about this sample? I get lost since there is a lot of files involve. Thank you.

    if (json == null) {
    // notify user
    } else {
    try {
    // parse json here.

    } catch (JSONException e) {
    Toast.makeText(this,”Error Connecting to server”,Toast.LENGTH_SHORT).show();
    }

    }

  • coolrandy

    android:background=”@color/sliding_list_divider_color” , sorry, I cannot find where ‘sliding_list_divider_color’ is defined?It is not in ‘colors.xml’ , can you tell me please?

  • Pingback: 안드로이드 ViewPager | 한글로의 개발노트

  • Ashutosh

    How can we set images of different height ? can you help on this ?

  • hyd

    Too much code for such simple thing.

  • androiddeveloper

    Error : Binary XML file line #62: Error inflating class com.androidopentutorials.imageslideshow.utils.CirclePageIndicator i dont know whats the problem.i added the library in android studio.could you create an android studio project and share this with us ? Thanks

  • white

    How to make full screen image when clicking image in this app?

  • Pingback: Tổng hợp android | 3s

  • Pingback: Getting NullPointerException in Activity where i'm receiving Json data [duplicate] - BlogoSfera

  • TAWFEH

    products.jsn how to modify the file contents to match the one that allows you to display my articles K2 joomla?

  • Manuel Silverio Fernandez

    This solution is a lot better: https://youtu.be/QCxvX06RAjk

  • Trường Nguyễn

    where could I find the “com.nostra13.universalimageloader.*”

  • Danial Habibi

    how to change the image Become Full like this one?where i can change the image size?

    • Niharika88

      hi,please send me this code

    • Milad Yarmohammadi

      use android:scaleType=”YOUR_CHOICE”
      in your imageView

  • Pingback: Imave View Fill Empty Space ViewPager Android - BlogoSfera

  • Pingback: Image View Fill Empty Space ViewPager Android - BlogoSfera

  • gur

    how to use above code in eclipse ?

  • gur

    from where i can add Universal Image Loader JAR file ?

  • Half Moon

    nice

  • Half Moon

    Find best android tutorial and example: http://www.viralandroid.com

  • Vicktor

    why I can’t run this project with android studio? I create new project with android studio but can’t running well.
    can you help me to this?

  • Khalid AlJahury

    Thanx alot, its a great tutorial
    But I have one question. How can I use images from my drawable folder instead of downloading them from the internet .

  • Jack

    Thanks a lot for this tutorial! By the way, we have used a new crumbling effect during transitions in our new project: https://github.com/Cleveroad/Bitutorial . Please, say what you think.

  • Pingback: Android Templates and advance concepts – vaidehipjoshi25

  • Pingback: ic218 » Полезные ссылки для Android разработчика

  • Ritesh Tiwari

    Thanks alot… i was looking for something like this … can you help me how can i achieve to play youtube video on click instead of details??

  • maddox nixon

    Hey Nice Work but how can i use this instead of the json file
    And how to make it update the images without having to exit the app and open again

    0) {
    // user node
    $response["trends"] = array();
    while ($row = mysqli_fetch_array($query_exec)) {
    $trends = array();
    $trends["id"] = $row ["id"];
    $trends["name"] = $row ["name"];
    $trends["imageUrl"] = $row ["photo"];;
    $count ++;
    array_push($response["trends"], $trends);
    }
    $response["success"] = 1;
    $response["message"] = “Found ” . $count . ” trends”;
    // echoing JSON response
    echo json_enCode($response);
    } else {
    // no trends found
    $response["success"] = 0;
    $response["message"] = “Found ” . $count . ” trends”;
    // echo no trends JSON
    echo json_enCode($response);
    }
    } else {
    // no trends found
    $response["success"] = 0;
    $response["message"] = “Error!!! You cannot do that!! Some data is needed”;

    // echo no trends JSON
    echo json_enCode($response);
    }
    mysqli_close($con);
    ?>

  • maddox nixon
  • Pingback: Image View Fill Empty Space ViewPager Android - Tutorial Guruji