Image slider using ViewPager with rest API in AndroidX

Hi, developer in this Android example I am sharing how to use image slider using ViewPager with rest API in AndroidX. I am getting a response from rest API in these API to have a JSONArray for Image and these JsonArray to show in ViewPager. So I have to make an Image slider using Viewpager. There is an easy Android example Image slider using view pager  with rest API,

So Let’s Start on the Solution! Image slider using ViewPager with rest API in AndroidX.

Step 1: Add ViewPager Layout in your XML File.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/Gray4"
    android:focusableInTouchMode="true"
    android:orientation="vertical">

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/Home_Page_View"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:layout_marginBottom="8dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"  />


    <LinearLayout
        android:id="@+id/SliderDots"
        android:layout_below="@+id/viewPager"
        android:orientation="horizontal"
        android:gravity="center_vertical|center_horizontal"
        android:layout_width="match_parent"
        android:layout_height="10dp"/>

</LinearLayout>

Step 2: Add these Codes in your Main Java file and implement the view pager.

in java file, we use Vollye request to getting a response from API and add this on view pager. Add these list  data according to dots in slider bottom

public class Home_Tab extends Fragment implements  ViewPagerEx.OnPageChangeListener{

    ViewPager viewPager;
    LinearLayout sliderDotspanel;
    private int dotscount;
    private ImageView[] dots;

    RequestQueue rq;
    List<SliderUtils> sliderImg;
    ViewPagerAdapter viewPagerAdapter;
    private RecyclerView firstRecyclerView;
    private HomeAdupter rAdapter;


    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_home__tab, container,
                false);
        /*hare used session to check user id log in or not
         * and save email*/
//        SessionManagement sessionManagement= new SessionManagement();
//        Token= sessionManagement.getSavedToken(getActivity());
        sliderImg = new ArrayList<>();
        viewPager = (ViewPager)rootView.findViewById(R.id.Home_Page_View);
        sliderDotspanel = (LinearLayout) rootView.findViewById(R.id.SliderDots);
        // Setup and Handover data to recyclerview
        firstRecyclerView = (RecyclerView) rootView.findViewById(R.id.Home_RecyclerView);
        firstRecyclerView.setHasFixedSize(true);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {

                for(int i = 0; i< dotscount; i++){
                    dots[i].setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.inactive_dot));
                }

                dots[position].setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.active_dot));

            }
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        if (AppStatus.getInstance(getActivity()).isOnline()) {
            HomeDetails();

            //           Toast.makeText(this,"You are online!!!!",Toast.LENGTH_LONG).show();

        } else {

            ContextThemeWrapper ctw = new ContextThemeWrapper( getActivity(), R.style.Theme_AlertDialog);
            final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(ctw);
            alertDialogBuilder.setTitle("No internet connection");
            alertDialogBuilder.setMessage("Check your  internet connection or try again");
            alertDialogBuilder.setNegativeButton("Setting", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
                }
            });
            alertDialogBuilder.setPositiveButton("Re Try", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    HomeDetails();
                }
            });
            alertDialogBuilder.show();
        }
        // Do something else
        return rootView;
    }

    // Get Request For JSONObject
    public void HomeDetails(){
        final ProgressDialog loading = new ProgressDialog(getActivity());
        loading.setMessage("Please Wait...");
        loading.setCanceledOnTouchOutside(false);
        loading.show();
        JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, ConfiURL.Home_Screen_URL, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.d("Response", response.toString());

                try {
                    Log.d("JSON", String.valueOf(response));
                    loading.dismiss();
                    String Error = response.getString("httpStatus");
                    if(Error.equals("OK")){
                        JSONObject Body = response.getJSONObject("body");
                        JSONArray banners = Body.getJSONArray("banners");
                        onPostbanners(banners);
                       

                    }else if(Error.equals("")||Error.equals(null)){

                    }else {

                    }



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

                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                loading.dismiss();
                VolleyLog.d("Error", "Error: " + error.getMessage());
                if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                    ContextThemeWrapper ctw = new ContextThemeWrapper( getActivity(), R.style.Theme_AlertDialog);
                    final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(ctw);
                    alertDialogBuilder.setTitle("No connection");
                    alertDialogBuilder.setMessage(" Connection time out error please try again ");
                    alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                        }
                    });
                    alertDialogBuilder.show();
                }
            }
        })
        {
            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", Token);
                return headers;
            }
        };
        RequestQueue queue = Volley.newRequestQueue(getActivity());
        queue.add(req);
    }

    protected void onPostbanners(JSONArray result) {
        for(int i = 0; i < result.length(); i++){
            SliderUtils sliderUtils = new SliderUtils();
            try {
                JSONObject jsonObject = result.getJSONObject(i);
                sliderUtils.setSliderImageUrl(jsonObject.getString("thumbnailImageUrl"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            sliderImg.add(sliderUtils);
        }
        viewPagerAdapter = new ViewPagerAdapter(sliderImg, getActivity());
        viewPager.setAdapter(viewPagerAdapter);
        dotscount = viewPagerAdapter.getCount();
        dots = new ImageView[dotscount];
        for(int i = 0; i < dotscount; i++){
            dots[i] = new ImageView(getActivity());
            dots[i].setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.inactive_dot));
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(8, 0, 8, 0);
            sliderDotspanel.addView(dots[i], params);
        }
        dots[0].setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.active_dot));
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}

Step 3: Create a Viewpager Adapter class.

InViewPager Adapter class we can get the value and set on the card. and also add click on Listener on the view pager item and open its details page with full details. It means we handling the card click listener on.

public class ViewPagerAdapter extends PagerAdapter {

    private Activity mActivity;
    private LayoutInflater layoutInflater;
    private List<SliderUtils> sliderImg;
    private ImageLoader imageLoader;
    private static final int TYPE_EVENT = 1;
    private static final int TYPE_VIDEOS = 2;
    private static final int TYPE_ARTICLES = 3;
    private static final int TYPE_CASESTUDY = 4;
    private static final int TYPE_BLOGS = 5;
    private static final int TYPE_TESTIMONIALS = 6;
    private static final int TYPE_DEFAULT = 7;


    public ViewPagerAdapter(List sliderImg, Activity context) {
        this.sliderImg = sliderImg;
        this.mActivity = context;
    }

    @Override
    public int getCount() {
        return sliderImg.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {

        layoutInflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.custom_layout, null);
        SliderUtils utils = sliderImg.get(position);
        ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
        imageLoader = CustomVolleyRequest.getInstance(mActivity).getImageLoader();
        imageLoader.get(utils.getSliderImageUrl(), ImageLoader.getImageListener(imageView, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));


        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SliderUtils utils = sliderImg.get(position);
                String bannerType = utils.getBannerType();
                String id = utils.getBannerID();
                if (bannerType.equalsIgnoreCase("event")) {
                    Intent intent = new Intent(mActivity, EventDetails_Screen.class);
                    intent.putExtra("id", id);
                    intent.putExtra("Tab", "Tab1");
                    intent.putExtra("isLaunchedFromHome",true);
                    mActivity.startActivity(intent);
                    mActivity.overridePendingTransition(R.anim.left_slide, R.anim.right_slide);
                    mActivity.finish();
                } else if (bannerType.equalsIgnoreCase("videos")) {
                    Intent intent = new Intent(mActivity, Video_Play.class);
                    intent.putExtra("id", id);
                    intent.putExtra("isLaunchedFromHome",true);
                    mActivity.startActivity(intent);
                    mActivity.overridePendingTransition(R.anim.left_slide, R.anim.right_slide);
                    mActivity.finish();
                } else if (bannerType.equalsIgnoreCase("articles")) {
                    Intent intent = new Intent(mActivity, Artical_Details.class);
                    intent.putExtra("id",id);
                    intent.putExtra("isLaunchedFromHome",true);
                    mActivity.startActivity(intent);
                    mActivity.overridePendingTransition(R.anim.left_slide, R.anim.right_slide);
                    mActivity.finish();
                } else if (bannerType.equalsIgnoreCase("case studies")) {
                    Intent intent = new Intent(mActivity, CaseStudeisDetails.class);
                    intent.putExtra("id", id);
                    intent.putExtra("isLaunchedFromHome",true);
                    mActivity.startActivity(intent);
                    mActivity.overridePendingTransition(R.anim.left_slide, R.anim.right_slide);
                    mActivity.finish();
                } else if (bannerType.equalsIgnoreCase("blogs")) {
                    Intent intent = new Intent(mActivity, Blog_Details.class);
                    intent.putExtra("id", id);
                    intent.putExtra("isLaunchedFromHome",true);
                    mActivity.startActivity(intent);
                    mActivity.overridePendingTransition(R.anim.left_slide, R.anim.right_slide);
                    mActivity.finish();
                } else if (bannerType.equalsIgnoreCase("news")) {
                    Intent intent = new Intent(mActivity, News_Details.class);
                    intent.putExtra("id", id);
                    intent.putExtra("isLaunchedFromHome",true);
                    mActivity.startActivity(intent);
                    mActivity.overridePendingTransition(R.anim.left_slide, R.anim.right_slide);
                    mActivity.finish();
                }else if (bannerType.equalsIgnoreCase("white papers")) {
                    Intent intent = new Intent(mActivity, Whitepapers_Details.class);
                    intent.putExtra("id", id);
                    intent.putExtra("isLaunchedFromHome",true);
                    mActivity.startActivity(intent);
                    mActivity.overridePendingTransition(R.anim.left_slide, R.anim.right_slide);
                    mActivity.finish();
                }
            }
        });
        ViewPager vp = (ViewPager) container;
        vp.addView(view, 0);
        return view;

    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {

        ViewPager vp = (ViewPager) container;
        View view = (View) object;
        vp.removeView(view);

    }
}

Step 4:  Slider Data Object Class Source code.

public class SliderUtils {

    String sliderImageUrl;
    String bannerType;
    String bannerID;

    public String getBannerID() {
        return bannerID;
    }

    public void setBannerID(String bannerID) {
        this.bannerID = bannerID;
    }

    public String getBannerType() {
        return bannerType;
    }

    public void setBannerType(String bannerType) {
        this.bannerType = bannerType;
    }

    public String getSliderImageUrl() {
        return sliderImageUrl;
    }

    public void setSliderImageUrl(String sliderImageUrl) {
        this.sliderImageUrl = sliderImageUrl;
    }
}
Facebooktwitterredditpinterestlinkedinmail
Recommended
Hii developer in this Android tutorial I am sharing how…