Last updated on August 28th, 2020 at 05:13 pm

In this tutorial, I can explain to you how we can add image slider in Android Application. For this tutorial, I am using an image slider plugin developed by Shivam Srivastava.

To implement image slider in your Android Application follow below simple steps. Implementation of image slider is very easy and also I am loading an image from the server using OKHTTP3. If you did not read my last post in which I explain how we can send and get data using OKHTTP3 you can read that from this link.

Step 1. Create a new Android project (In my case my project name is AndroidImageSlider).

Step 2. Add library OKHTTP3 and ImageSlider in your build.gradle(App) and add code in dependencies as shown below

dependencies {
    /* Other lib....*/
    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
    implementation 'com.shivam.library:imageslider:1.1@aar'
}

Step 3. Once we add our dependencies and synchronize our project we are ready to code our application. Now open your AndroidManifest.xml and add Internet permission.

<uses-permission android:name="android.permission.INTERNET" />

Step 4. Now we can create a Package name model in which we can create BannerModel(getter and setter) class which hold id and image URL which we load for the server using web API.

package com.imageslider.model;

public class BannerModel {
    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    String url;
}

Step 5. Now open the activity_main.xml file and we call our image slider view here as shown below

<com.shivam.library.imageslider.ImageSlider
    android:layout_width="match_parent"
    android:layout_height="550dp"
    android:id="@+id/pager"
 />

Step 6. Now in our MainActivity.java class, we first find or our ImageSlider and after that, we can load data from API and set that data into Adapter and we also create Fragment inside or MainActivity Class as shown in below code.

package com.imageslider;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.imageslider.model.BannerModel;
import com.shivam.library.imageslider.ImageSlider;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    ArrayList<BannerModel> bannerModelsArray;
    ImageSlider slider;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        slider = (ImageSlider) findViewById(R.id.pager);

        try {
            getImages();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getImages() throws IOException {

        String url = "https://cakeapi.trinitytuts.com/api/slider";

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .header("Accept", "application/json")
                .header("Content-Type", "application/json")
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String mMessage = e.getMessage().toString();
                Log.w("failure Response", mMessage);
                //call.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                final String mMessage = response.body().string();

                Log.e("Response", String.valueOf(response.code()));


                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        bannerModelsArray = new ArrayList<>();

                        JSONObject parent = null;
                        try {
                            parent = new JSONObject(mMessage);

                            // Banners
                            JSONArray banners = parent.getJSONArray("banners");
                            for (int i = 0; i < banners.length(); i++){
                                JSONObject data = banners.getJSONObject(i);
                                BannerModel bannerModel = new BannerModel();
                                bannerModel.setUrl(data.getString("url"));
                                bannerModelsArray.add(bannerModel);
                            }

                            // Set banner
                            SectionsPagerAdapter  mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), bannerModelsArray.size());
                            slider.setAdapter(mSectionsPagerAdapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {   // adapter to set in ImageSlider

        int imageCount = 0;

        public SectionsPagerAdapter(FragmentManager fm, int count) {
            super(fm);

            imageCount = count;
        }

        @Override
        public Fragment getItem(int position) {

            BannerModel banner = (BannerModel)bannerModelsArray.get(position);
            return PlaceholderFragment.newInstance(banner.getUrl());
        }

        @Override
        public int getCount() {

            return imageCount;
        }

        @Override
        public CharSequence getPageTitle(int position) {

            return null;
        }
    }

    // Image fragment
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {

        }

        public static PlaceholderFragment newInstance(String pic) {

            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putString("index", pic);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            View rootView = inflater.inflate(R.layout.fragment_main3, container, false);
            Bundle args = getArguments();
            String image = args.getString("index", "https://prfashionweb.files.wordpress.com/2018/11/new-arri-bannr.jpg");
            ImageView imageView=(ImageView)rootView.findViewById(R.id.image);

            Glide
                    .with(getActivity())
                    .load(image)
                    .into(imageView);
            return rootView;
        }
    }
}

Here is code for the fragment_main3.xml file which holds ImageView for Slider.

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

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/image"
        android:scaleType="centerCrop"
        />

</RelativeLayout>

You can download code from the above download link. Hope this post helps you.