How to create Endless RecyclerView with multiple Image and Text using Volley and Glide

In this tutorial, I will show you how to create Endless scroll-able list with contains images or text. To display a list RecyclerView is the best option. RecyclerView have option for customization and control behavior of item. I will use Volley and Glide library to fetch image from server. With Volley you can get data from server as JSON, XML, header, image etc. Remember i am using Volley and Glide to show you how to use this two library, you can either use volley only or Glide only. In this tutorial our aim is to create a list which contains image and text inside CardView.Below are the step i will discuss with you.




1) Create Endless RecyclerView with Adapter.
2) Create Two type of CardView- Image and Text
2) Add some Static item into RecyclerView.
3) Add some Dynamic item like image using volley library.
4) Fetch image from server using Glide library.
5) Run App in Real Device using USB Debugging.

Login & Download source code

download-code350-100





Create Endless RecyclerView with Adapter

Create new Project in android studio. Name of my project is volleyrecyclerview. First open App Module Gradle and add dependency for RecyclerView, CardView, Volley and Glide. Add this line in dependency. Then open activity_xml and place RecyclerView and a ProgressBar. Also Add Internet permissin in Androidmanifest.xml file

    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.android.support:design:24.2.1'
    /// volley
    compile 'com.android.volley:volley:1.0.0'
    // Glide
    compile 'com.github.bumptech.glide:glide:3.7.0'
    /// cardview 
    compile 'com.android.support:cardview-v7:24.2.1'
    /// recyclerview
    compile 'com.android.support:recyclerview-v7:24.2.1'

<android.support.design.widget.CoordinatorLayout 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:id="@+id/collapsing_toolbar"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">


        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="8dp">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scrollbars="none" />
            <ProgressBar
                android:id="@+id/progressBar1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:visibility="gone"/>

        </RelativeLayout>



</android.support.design.widget.CoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="blueappsoftware.volleyrecyclerview">
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name=".AppController"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Now define RecyclerView and Progress bar in MainActivity.java class. To show item inside RecyclerView we need ArrayList. The ArrayList can hold item like Text and Image, for that we have to create a Modal that tells Arraylist whether it is Text OR Image. Create new Model.java class and write code.

package blueappsoftware.volleyrecyclerview;

/**
 * Created by jain on 30-Mar-17.
 */
public class Model {

    public static final int TEXT_TYPE=0;
    public static final int IMAGE_TYPE=1;

    public int type;
    public String data;

    public Model(int type, String data)
    {
        this.type=type;
        this.data=data;

    }
}

Create Two type of CardView- Image and Text

We have to create two layout, One for image type item and second for text type item in ArrayList. To show material design use CardView. CardView adds shadow and curve in layout.

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    card_view:cardElevation="5dp">

        <TextView
            android:id="@+id/type"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="8dp"
            android:paddingRight="8dp"
            android:paddingTop="10dp"
            android:gravity="left"
            android:textStyle="bold"
            android:textSize="17sp"
            android:maxLines="3"
            android:textColor="#000000"
            android:fontFamily="sans-serif-condensed" />

</android.support.v7.widget.CardView>


<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    card_view:cardElevation="5dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/type"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="8dp"
            android:paddingRight="8dp"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:gravity="left"
            android:textStyle="bold"
            android:textSize="17sp"
            android:maxLines="3"
            android:textColor="#000000"
            android:fontFamily="sans-serif-condensed" />

        <ImageView
            android:id="@+id/background"
            android:layout_width="match_parent"
            android:layout_height="170dp"
            android:scaleType="centerCrop"
            android:src="@drawable/blueapp"
            android:layout_marginBottom="2dp"/>

    </LinearLayout>

</android.support.v7.widget.CardView>

Add some Static item into RecyclerView

To add static item in Arraylist use arraylist.add method. Because we need endless RecyclerView show we will add onScrollListener in RecyclerView. When user start scrolling a request will send to a URL using Volley that sendback a image path in response. then fetch actual image from the image path using Glide. Below is Complete code of MainActivity.java

package blueappsoftware.volleyrecyclerview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private String TAG ="mainactivity";
    private ProgressBar progressBar;
    private RecyclerView recyclerView;
    private ArrayList<Model> list;
    private RecyclerAdapter adapter;
    private LinearLayoutManager mLayoutManager;
    private boolean loading = true;
    private int pastVisiblesItems, visibleItemCount, totalItemCount, PageCount=1, PageCountLock=0;


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

        progressBar = (ProgressBar) findViewById(R.id.progressBar1);

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);

        list= new ArrayList<>();
          list.add(new Model(Model.TEXT_TYPE,"This is Text only Cardview inside Endless RecyclerView. Scroll down to endless view. For more details You can visit www.blueappsoftware.in/android"));
          list.add(new Model(Model.IMAGE_TYPE,"http://blueappsoftware.in/android/downloadcode/DemoImage/learnwithkamalbunkar.png"));
          list.add(new Model(Model.IMAGE_TYPE,"http://blueappsoftware.in/android/downloadcode/DemoImage/bannerBlueapp.png"));
          list.add(new Model(Model.TEXT_TYPE,"This is Text only Cardview inside Endless RecyclerView. Scroll down to endless view. For more details You can visit www.blueappsoftware.in/android"));
          list.add(new Model(Model.TEXT_TYPE,"This is Text only Cardview inside Endless RecyclerView. Scroll down to endless view. For more details You can visit www.blueappsoftware.in/android"));
          list.add(new Model(Model.IMAGE_TYPE,"http://blueappsoftware.in/android/downloadcode/DemoImage/blueapp.png"));
          list.add(new Model(Model.TEXT_TYPE,"Scroll down will lead to Endless scrolling with fetching image from server. Scroll down to endless view. For more details You can visit www.blueappsoftware.in/android"));


        adapter = new RecyclerAdapter(list,this);
        mLayoutManager = new LinearLayoutManager(MainActivity.this, OrientationHelper.VERTICAL, false);

        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(adapter);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
        {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy)
            {
                //  Log.e("...", " onscroll dx " + dx +" dy "+ dy);
                try{
                    if(dy > 0) //check for scroll down
                    {
                        visibleItemCount = mLayoutManager.getChildCount();
                        totalItemCount = mLayoutManager.getItemCount();
                        pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
                        if (loading)
                        {   //  Log.e(TAG, " page count lock "+PageCountLock);
                            progressBar.setVisibility(View.VISIBLE);
                            if ( pastVisiblesItems >= (totalItemCount/3) ){
                                Log.e(TAG," on scroll visible - "+ visibleItemCount+"  total "+ totalItemCount+"  pastvisible "+pastVisiblesItems );
                                getDataFromVolley( );
                            }
                            if ( (visibleItemCount + pastVisiblesItems) >= totalItemCount)
                            {
                                // loading = false;
                                Log.e("...", "Last Item readed in list **** ");
                            }
                        }
                    }
                }catch (Exception e){
                    Log.e(TAG,"scrooll action "+ e.toString());
                }

            }
        });

    }

    private void getDataFromVolley(){

        /// here are volley that get string dta from server...
        // you can get JSON, XML or Image from server....

        // this string Tag used to control volley request like cancel the request
        String tag_string_req = "volley_string_req";
        String url ="http://blueappsoftware.in/android/downloadcode/DemoImage/getImagePath.html";
        StringRequest strReq = new StringRequest(Request.Method.GET,  url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.e(TAG, "Get response from volley add to recycleerview "+response.toString());
                list.add(new Model(Model.IMAGE_TYPE,response.toString()));
                adapter.notifyDataSetChanged();
                progressBar.setVisibility(View.INVISIBLE);
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.e(TAG, "Error: " + error.getMessage());
            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

    }
    @Override
    public void onClick(View v) {
        int id = v.getId();

    }

}

Create RecyclerVew Adpter

Create RecyclerAdapter.java class in android project. ArralList item are pass to RecyclerAdapter which is responsible to show. display item to user. Technically i can say Adapter band view and item to activity_main.xml layout. Define text_type.xml and image_type.xml element in RecyclerAdapter.

package blueappsoftware.volleyrecyclerview;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;

/**
 * Created by jain on 30-Mar-17.
 */

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private ArrayList<Model> dataSet;
    Context mContext;
    int total_types;
    MediaPlayer mPlayer;
    private boolean fabStateVolume = false;

    public static class TextTypeViewHolder extends RecyclerView.ViewHolder {

        TextView txtType;
        CardView cardView;

        public TextTypeViewHolder(View itemView) {
            super(itemView);
            this.txtType = (TextView) itemView.findViewById(R.id.type);
            this.cardView = (CardView) itemView.findViewById(R.id.card_view);
        }
    }

    public static class ImageTypeViewHolder extends RecyclerView.ViewHolder {

        TextView txtType;
        ImageView image;

        public ImageTypeViewHolder(View itemView) {
            super(itemView);
            this.txtType = (TextView) itemView.findViewById(R.id.type);
            this.image = (ImageView) itemView.findViewById(R.id.background);
        }
    }


    public RecyclerAdapter(ArrayList<Model> data, Context context) {
        this.dataSet = data;
        this.mContext = context;
        total_types = dataSet.size();

    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view;
        switch (viewType) {
            case Model.TEXT_TYPE:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_type, parent, false);
                return new TextTypeViewHolder(view);
            case Model.IMAGE_TYPE:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_type, parent, false);
                return new ImageTypeViewHolder(view);
        }
        return null;
    }


    @Override
    public int getItemViewType(int position) {

        switch (dataSet.get(position).type) {
            case 0:
                return Model.TEXT_TYPE;
            case 1:
                return Model.IMAGE_TYPE;
            default:
                return -1;
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int listPosition) {

        final Model object = dataSet.get(listPosition);
        if (object != null) {
            switch (object.type) {
                case Model.TEXT_TYPE:
                    ((TextTypeViewHolder) holder).txtType.setText(object.data);
                    ((TextTypeViewHolder) holder).txtType.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            // on click event open another activity or something

                        //    Intent nextScreen = new Intent(mContext, OpenFullDetail.class);
                        //    mContext.startActivity(  nextScreen);

                        }
                    });


                    break;
                case Model.IMAGE_TYPE:
                    ((ImageTypeViewHolder) holder).txtType.setText(" This is Image with Text type Cardview. Fetch Image using Volley and Glide.");
                    // ((ImageTypeViewHolder) holder).image.setImageResource(object.data);
                    Glide.with(mContext).load(object.data)
                            .thumbnail(0.5f)
                            .crossFade()
                            //.dontAnimate()
                            .placeholder(R.drawable.blueapp)
                            // .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(((ImageTypeViewHolder) holder).image);

                    ((ImageTypeViewHolder) holder).image.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            // intent to start new activity for youtube player....
                            // on click event open another activity or something

                            //    Intent nextScreen = new Intent(mContext, OpenFullDetail.class);
                            //    mContext.startActivity(  nextScreen);
                        }
                    });


                    break;
            }
        }

    }

    @Override
    public int getItemCount() {
        return dataSet.size();
    }


}

Create Volley Request controller

Create AppController.java class in android project. this will respond to volley request and you can take action accordingly.

package blueappsoftware.volleyrecyclerview;

/**
 * Created by jain on 30-Mar-17.
 */
import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

Add some Dynamic item like image using volley library.

When user scroll to the list onScrollListen start sending request for new data to server.I am sending request to this HTML Page. The HTML page contains only path of the image as http://blueappsoftware.in/android/downloadcode/DemoImage/learnwithkamalbunkar.png. So when Volley get this image path as response Volley start fetching image from http://blueappsoftware.in/android/downloadcode/DemoImage/learnwithkamalbunkar.png. when new image available it added to RecyclerView so user will see a endless scrolling.

private void getDataFromVolley(){

        /// here are volley that get string dta from server...
        // you can get JSON, XML or Image from server....

        // this string Tag used to control volley request like cancel the request
        String tag_string_req = "volley_string_req";
        String url ="http://blueappsoftware.in/android/downloadcode/DemoImage/getImagePath.html";
        StringRequest strReq = new StringRequest(Request.Method.GET,  url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.e(TAG, "Get response from volley add to recycleerview "+response.toString());
                list.add(new Model(Model.IMAGE_TYPE,response.toString()));
                adapter.notifyDataSetChanged();
                progressBar.setVisibility(View.INVISIBLE);
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.e(TAG, "Error: " + error.getMessage());
            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

    }
    




Run App Code

Run app on Real device, you will see a endless scrolling.

Login & Download source code

download-code350-100

SUBSCRIBE FOR FREE ANDROID COURSE, Inbox 15 lesson & Video

* indicates required






Posted in andorid.

I Am Post Graduation (M.Tech. C.S.E) from VNIT, Nagpur. I Have Published Two Research Paper On International Journal. My Apps on Google Play Store- Sanyukt Parivar(Mp Police ), NOTOtag- Digital Chhindwara, The Tubby-VoiceRecognizer & More.
Contact me at kamal.bunkar@blueappsoftware.in

33 Comments

  1. I love your blog.. very nice colors & theme. Did you create this
    website yourself or did you hire someone to do it for you?
    Plz respond as I’m looking to create my own blog and would like to find
    out where u got this from. appreciate it

  2. Pretty great post. I just stumbled upon your weblog and wanted to say
    that I’ve truly loved browsing your blog posts.
    In any case I’ll be subscribing for your feed and I hope you write once more very soon!

  3. Hi there! This post could not be written any better!
    Reading through this post reminds me of my good old room mate!
    He always kept talking about this. I will forward this article to him.
    Fairly certain he will have a good read. Thank you for sharing!

  4. Hi there! Quick question that’s totally off topic.
    Do you know how to make your site mobile friendly?
    My weblog looks weird when browsing from my iphone4.
    I’m trying to find a template or plugin that might
    be able to fix this issue. If you have any recommendations, please share.
    Thank you!

  5. This is really attention-grabbing, You are an overly skilled blogger.
    I have joined your feed and look forward to in the hunt
    for extra of your great post. Also, I have shared your site in my social networks

  6. I’m really enjoying the theme/design of your blog.

    Do you ever run into any browser compatibility issues?

    A few of my blog audience have complained about my site not
    working correctly in Explorer but looks great in Chrome.
    Do you have any solutions to help fix this issue?

  7. I was recommended this web site by my cousin. I’m
    not sure whether this post is written by him as no one else
    know such detailed about my problem. You are wonderful!

    Thanks!

  8. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything. I truly enjoy reading your
    blog and I look forward to your new updates.

  9. Having read this I thought it was very informative. I appreciate you finding the time and
    energy to put this short article together. I once again find myself personally spending a lot of time both reading and posting comments.
    But so what, it was still worthwhile!

  10. hi! may i know is your code complete? because i run the program and does nothing, i have download the given source code.

    • Yes this code is working…You have to create file on php server to store FCM key into your database for future use. First check on your android studio log whether FCM token is printing OR not. If it is printing in log than send token to your web server.

  11. Good day! I could have sworn I’ve been to
    this website before but after going through
    a few of the articles I realized it’s new to me.

    Nonetheless, I’m certainly delighted I found it and I’ll be book-marking it and checking back regularly!

  12. Spot on with this write-up, I absolutely feel this website needs much more attention. I’ll probably be returning to read
    through more, thanks for the info!

  13. Hey very cool website!! Man .. Excellent ..
    Amazing .. I will bookmark your site and take the feeds additionally?
    I am glad to search out numerous useful info here
    in the submit, we need work out more strategies
    on this regard, thanks for sharing. . . . . .

  14. Pingback: ExoPlayer Android Example- Best Alternative of VideoView By Kamal

  15. Pingback: Simplest way to get WordPress Post in Android App- REST API

  16. I just like the helpful information you supply to your articles.

    I’ll bookmark your blog and test once more here frequently.
    I’m fairly sure I will learn many new stuff proper here!
    Good luck for the following!

Comments are closed.