Android Image Slider From URL | Fetch Image From Server URL

android recyclerview section header, android image slider from url, android multi column listview, android recyclerview multi column

This tutorial is about Android Image Slider From URL.

In this tutorial, we will how to fetch images from server url to image slider with view pager in android studio.

We will load images from the URL and will show them in viewpager.

Glide library will help us to load images from the server URL.

Our image slider will be able to show the automatic slideshow.

This image slider enables user to swipe left or right to change the current image.

Automatic Slider

Read this tutorial to make image slide from in built images.

Step 1. Gradle File Changes

We are going to use two libraries in this example.

One is Jack Wharton for making sliding layout with viewpager.

Another is Glide to load the images easily and smoothly from the URL.

Add below three lines in your build.gradle(Module: app) file

implementation 'com.github.JakeWharton:ViewPagerIndicator:2.4.1'
implementation 'com.github.bumptech.glide:glide:4.7.1'
implementation 'com.android.support:design:27.1.0'

Step 2. Adding Permission

To fetch the images from server, we need to use internet.

So, we have to define internet permission in AndroidManifest.xml file

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

Step 3. Slider Layout

Create a new layout xml file under res->layout directory.

Name this file as slidingimages_layout.xml

Write down the below source code in it.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="1dip" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:adjustViewBounds="true"
        android:layout_gravity="center"
        android:src="@mipmap/ic_launcher"
        android:scaleType="centerCrop" />
</FrameLayout>

This code represent the single slide layout of the viewpager.

Every slide of the viewpager will use this single layout only.

Step 4. Adapter Class

Let us create an adapter class which will give necessary data to populate the viewpager slides.

Make one new class named SlidingImage_Adapter.java class

Copy the below source code in it.

import android.content.Context;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;



/**
 * Created by Parsania Hardik on 23/04/2016.
 */
public class SlidingImage_Adapter extends PagerAdapter {


    private String[] urls;
    private LayoutInflater inflater;
    private Context context;


    public SlidingImage_Adapter(Context context, String[] urls) {
        this.context = context;
        this.urls = urls;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public int getCount() {
        return urls.length;
    }

    @Override
    public Object instantiateItem(ViewGroup view, int position) {
        View imageLayout = inflater.inflate(R.layout.slidingimages_layout, view, false);

        assert imageLayout != null;
        final ImageView imageView = (ImageView) imageLayout
                .findViewById(R.id.image);


        Glide.with(context)
                .load(urls[position])
                .into(imageView);

        view.addView(imageLayout, 0);

        return imageLayout;
    }

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

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
    }

    @Override
    public Parcelable saveState() {
        return null;
    }


}

Now let us understand the above code

consider the below line

private String[] urls;

It defines the string array called urls. This string variable contains the urls of the images.

I have made this string array with it’s values in the MainActivity.java class which we will see in the next step.

instantiateItem() method will create every slide of the viewpager.

Coding lines for this method is as following

 @Override
    public Object instantiateItem(ViewGroup view, int position) {
        View imageLayout = inflater.inflate(R.layout.slidingimages_layout, view, false);

        assert imageLayout != null;
        final ImageView imageView = (ImageView) imageLayout
                .findViewById(R.id.image);


        Glide.with(context)
                .load(urls[position])
                .into(imageView);

        view.addView(imageLayout, 0);

        return imageLayout;
    }

First of all, compiler will find the whole slide view with the help of the below line

 View imageLayout = inflater.inflate(R.layout.slidingimages_layout, view, false);

Here, I have used that layout xml file (slidingimages_layout.xml) which we have created in step 3.

After this, compiler will find the ImageView with the help of findViewById() method.

Now to fetch or load the image from url, compiler will execute following code

Glide.with(context)
     .load(urls[position])
     .into(imageView);

urls[position] will provide appropriate url of the image.

Above three lines will fetch the image and will show it in the imageview.

Step 5. Final Changes

Now all we need is to make some changes in activity_main.xml and MainActivity.java file

Copy and paste below code in activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_alignParentTop="true" />

        <com.viewpagerindicator.CirclePageIndicator
            android:id="@+id/indicator"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:gravity="bottom"
            android:padding="10dip"
            app:centered="true"
            app:fillColor="#df0623"
            app:pageColor="#fff"
            app:snap="false" />
    </RelativeLayout>
</RelativeLayout>

I have taken one viewpager in the main layout file.

Now we need to show indicator dots such that in just overlap the viewpager from the bottom of the slider.

For this, I have used relativelayout, so that we can overlap the necessary things properly.

Now write down the following coding lines in MainActivity.java file

import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.viewpagerindicator.CirclePageIndicator;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private static ViewPager mPager;
    private static int currentPage = 0;
    private static int NUM_PAGES = 0;

    private String[] urls = new String[] {"https://demonuts.com/Demonuts/SampleImages/W-03.JPG", "https://demonuts.com/Demonuts/SampleImages/W-08.JPG", "https://demonuts.com/Demonuts/SampleImages/W-10.JPG",
                                            "https://demonuts.com/Demonuts/SampleImages/W-13.JPG", "https://demonuts.com/Demonuts/SampleImages/W-17.JPG", "https://demonuts.com/Demonuts/SampleImages/W-21.JPG"};

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

        init();
    }

    private void init() {

        mPager = (ViewPager) findViewById(R.id.pager);
        mPager.setAdapter(new SlidingImage_Adapter(MainActivity.this,urls));

        CirclePageIndicator indicator = (CirclePageIndicator)
                findViewById(R.id.indicator);

        indicator.setViewPager(mPager);

        final float density = getResources().getDisplayMetrics().density;

//Set circle indicator radius
        indicator.setRadius(5 * density);

        NUM_PAGES = urls.length;

        // Auto start of viewpager
        final Handler handler = new Handler();
        final Runnable Update = new Runnable() {
            public void run() {
                if (currentPage == NUM_PAGES) {
                    currentPage = 0;
                }
                mPager.setCurrentItem(currentPage++, true);
            }
        };
        Timer swipeTimer = new Timer();
        swipeTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.post(Update);
            }
        }, 3000, 3000);

        // Pager listener over indicator
        indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                currentPage = position;

            }

            @Override
            public void onPageScrolled(int pos, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int pos) {

            }
        });

    }
}

Explanation of above code

Give your attention to the following line

 private String[] urls = new String[] {"https://demonuts.com/Demonuts/SampleImages/W-03.JPG", 
                                    "https://demonuts.com/Demonuts/SampleImages/W-08.JPG", 
                                               "https://demonuts.com/Demonuts/SampleImages/W-10.JPG",
                                            "https://demonuts.com/Demonuts/SampleImages/W-13.JPG", 
                                           "https://demonuts.com/Demonuts/SampleImages/W-17.JPG", 
                                           "https://demonuts.com/Demonuts/SampleImages/W-21.JPG"};

Here we are setting all the urls in one string array. We have used this string array in the adapter class as we have shown earlier.

Now consider init() method as per below

private void init() {

        mPager = (ViewPager) findViewById(R.id.pager);
        mPager.setAdapter(new SlidingImage_Adapter(MainActivity.this,urls));

        CirclePageIndicator indicator = (CirclePageIndicator)
                findViewById(R.id.indicator);

        indicator.setViewPager(mPager);

        final float density = getResources().getDisplayMetrics().density;

//Set circle indicator radius
        indicator.setRadius(5 * density);

        NUM_PAGES = urls.length;

        // Auto start of viewpager
        final Handler handler = new Handler();
        final Runnable Update = new Runnable() {
            public void run() {
                if (currentPage == NUM_PAGES) {
                    currentPage = 0;
                }
                mPager.setCurrentItem(currentPage++, true);
            }
        };
        Timer swipeTimer = new Timer();
        swipeTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.post(Update);
            }
        }, 3000, 3000);

        // Pager listener over indicator
        indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                currentPage = position;

            }

            @Override
            public void onPageScrolled(int pos, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int pos) {

            }
        });

    }

This method will first set the adapter to the viewpager object.

Then compiler will set the circle indicator to the viewpager object.

You can also set the radius of the circle indicator by using the below line

indicator.setRadius(5 * density);

Following line set the number of pages or slides.

NUM_PAGES = urls.length;

Following code is responsible to enable the automatic slider.

 // Auto start of viewpager
        final Handler handler = new Handler();
        final Runnable Update = new Runnable() {
            public void run() {
                if (currentPage == NUM_PAGES) {
                    currentPage = 0;
                }
                mPager.setCurrentItem(currentPage++, true);
            }
        };
        Timer swipeTimer = new Timer();
        swipeTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.post(Update);
            }
        }, 3000, 3000);

You can change the value from 3000 to other in above code to increase or decrease the time of the automatic slider.

Download Source Code For Android Image Slider From URL

[sociallocker]Download Source Code For ImageSlider From URL[/sociallocker]