How to Fetch Images from Server to Image Slider with ViewPager in Android Studio

Posted on: October 15, 2017 at 4:07 pm by Sanket Mhaddalkar - 9 Comments

How to Fetch Images from Server to Image Slider with ViewPager in Android Studio

 

In this article will see how to fetch images our server into our app with a networking library called Volley. Volley is an HTTP library that makes networking for Android apps easier and faster.

 

We will be making Custom Volley Request to send request to the server and get response to display the data in our app. Volley also help in caching response and load images that are fetched from the server. So lets get started by sending our first request with Volley Library in Android.

 

You can watch out our video tutorial on this article.

 

 

Steps and Source code for fetch images from server to Image Slider with ViewPager –

 

– First you need to create an API to output data from server that is to be fetched in our app.

 

– This is the output of our API (This Restful API is create with PHP and MySQL). Request URL: http://localhost/sliderjsonoutput.php

 

Json Output:

[
    {
        "id": "1",
        "title": "Slide 1",
        "description": "First of three slide",
        "image_url": "http:\/\/localhost\/sliderimg\/slide1.png"
    },
    {
        "id": "2",
        "title": "Slide 2",
        "description": "Second of three slide",
        "image_url": "http:\/\/localhost\/sliderimg\/slide2.png"
    },
    {
        "id": "3",
        "title": "Slide 3",
        "description": "Third of three slide",
        "image_url": "http:\/\/localhost\/sliderimg\/slide3.png"
    }
]

 

– Create new project in Android Studio (for eg. AndroidImageSliderFetch).

 

– Create an empty activity i.e MainActivity.

 

– Now we will add Volley Library to our android project.

 

– Add the following dependency to your apps build.gradle file and Sync the project.

 

dependencies {

    compile 'com.android.volley:volley:1.0.0'
}

 

– Also add INTERNET permission into your Manifest file.

 

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

 

– After that add ViewPager to your MainActivity layout file i.e activity_main.xml

 

activity_main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.test.imagesliderfetch.MainActivity">

<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="190dp"
android:layout_marginBottom="8dp"/>

<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="wrap_content"/>

</RelativeLayout>

 

– Then create a layout file to display images by right clicking on the layout folder and choose New > Layout resource file name it custom_layout.

 

custom_layout.xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="@mipmap/ic_launcher"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:id="@+id/imageView" />

</LinearLayout>

 

– Now create a simple model class to store th fetched data into objects.

 

SliderUtils.java file:

package com.test.imagesliderfetch;


public class SliderUtils {

    String sliderImageUrl;

    public String getSliderImageUrl() {
        return sliderImageUrl;
    }

    public void setSliderImageUrl(String sliderImageUrl) {
        this.sliderImageUrl = sliderImageUrl;
    }
}

 

– After that your need to create java file for Custom Volley Request. We will use singleton approach for requesting data and image loading functionality. For this we will be using RequestQueue and ImageLoader class from the volley library.

 

CustomVolleyRequest.java file:

package com.test.imagesliderfetch;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.ImageLoader;


public class CustomVolleyRequest {

    private static CustomVolleyRequest customVolleyRequest;
    private static Context context;
    private RequestQueue requestQueue;
    private ImageLoader imageLoader;

    private CustomVolleyRequest(Context context){

        this.context = context;
        this.requestQueue = getRequestQueue();

        imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {

            private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);

            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url, bitmap);
            }
        });

    }

    public static synchronized CustomVolleyRequest getInstance(Context context){

        if(customVolleyRequest == null){
            customVolleyRequest = new CustomVolleyRequest(context);
        }
        return customVolleyRequest;
    }

    public RequestQueue getRequestQueue(){

        if(requestQueue == null){

            Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024);
            Network network = new BasicNetwork(new HurlStack());
            requestQueue = new RequestQueue(cache, network);
            requestQueue.start();

        }
        return requestQueue;
    }

    public  void addToRequestQueue(Request req) {
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader(){

        return imageLoader;

    }

}

 

– We need to create an adapter to load the fetched images into our ViewPager. For this we will create a new class that extends PageAdapter.

 

ViewPagerAdapter.java file:

package com.test.imagesliderfetch;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;

import java.util.List;


public class ViewPagerAdapter extends PagerAdapter {

    private Context context;
    private LayoutInflater layoutInflater;
    private List<SliderUtils> sliderImg;
    private ImageLoader imageLoader;
    
	
    public ViewPagerAdapter(List sliderImg,Context context) {
        this.sliderImg = sliderImg;
        this.context = 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) context.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(context).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) {

                if(position == 0){
                    Toast.makeText(context, "Slide 1 Clicked", Toast.LENGTH_SHORT).show();
                } else if(position == 1){
                    Toast.makeText(context, "Slide 2 Clicked", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "Slide 3 Clicked", Toast.LENGTH_SHORT).show();
                }

            }
        });

        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);

    }
}

 

– Now final step is to setup the ViewPager with Adapter and send a request to our server to get the data in response into our MainActivity.

 

MainActivity.java file:

package com.test.imagesliderfetch;


import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

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

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

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

    RequestQueue rq;
    List<SliderUtils> sliderImg;
    ViewPagerAdapter viewPagerAdapter;

    String request_url = "http://localhost/sliderjsonoutput.php";

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

        rq = CustomVolleyRequest.getInstance(this).getRequestQueue();

        sliderImg = new ArrayList<>();

        viewPager = (ViewPager) findViewById(R.id.viewPager);

        sliderDotspanel = (LinearLayout) findViewById(R.id.SliderDots);

        sendRequest();


        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(getApplicationContext(), R.drawable.nonactive_dot));
                }

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

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }


    public void sendRequest(){

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, request_url, null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

                for(int i = 0; i < response.length(); i++){

                    SliderUtils sliderUtils = new SliderUtils();

                    try {
                        JSONObject jsonObject = response.getJSONObject(i);

                        sliderUtils.setSliderImageUrl(jsonObject.getString("image_url"));

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

                    sliderImg.add(sliderUtils);

                }

                viewPagerAdapter = new ViewPagerAdapter(sliderImg, MainActivity.this);

                viewPager.setAdapter(viewPagerAdapter);

                dotscount = viewPagerAdapter.getCount();
                dots = new ImageView[dotscount];

                for(int i = 0; i < dotscount; i++){

                    dots[i] = new ImageView(MainActivity.this);
                    dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.nonactive_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(getApplicationContext(), R.drawable.active_dot));

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        CustomVolleyRequest.getInstance(this).addToRequestQueue(jsonArrayRequest);

    }

}

 

Hope you find this article helpful. Join us on Facebook, Twitter and Google+ to get more updates on Android Development Tutorials.

 



About Author:

I am Certified Java Developer. I Develop Android Applications and Websites. I also love blogging so as to share my experiences with others.



Subscribe to our Newsletter

Join our mailing list to receive
the latest news and updates from our team.