Android load more data on scroll down event in a Gridview

We all know that we should not load large number of records in a single call to populate a list or view. We should always load records in small chunks, and for this we need to implement pagination in our code. generally we shows previous/next link or page number at the bottom of the list or top of list and by clicking on that link user is redirected to next or previous page.

In an android app we loads more data when user scroll down on an activity. in the previous articles we have seen that how to use a Grid View component to show records in grid format. If you have not read that article please read that articles first. Android GridView Layout Tutorial, How to create image gallery in android

Now we will learn how to load more data on scroll down event. We will create a new class called EndlessScrollListener. This class will be called on setOnScrollListener event of a gridview.

In this class we are using volley to fetch data from server.

  
    public class EndlessScrollListener implements AbsListView.OnScrollListener {

        private int visibleThreshold = 6;
        private int currentPage = 1;
        private int previousTotal = 0;
        private boolean loading = true;

        public EndlessScrollListener() {
        }

        public EndlessScrollListener(int visibleThreshold) {
            this.visibleThreshold = visibleThreshold;
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {
            if (loading) {
                if (totalItemCount > previousTotal) {
                    loading = false;
                    previousTotal = totalItemCount;
                    currentPage++;
                }
            }

            //Log.v("firstVisibleItem",Integer.toString(firstVisibleItem));
            //Log.v("visibleItemCount",Integer.toString(visibleItemCount));
            //Log.v("totalItemCount",Integer.toString(totalItemCount));

            Boolean c = (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold);
            //Log.v("result", String.valueOf(c));

            if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
                // I load the next page of gigs using a background task,
                // but you can call any function here.


                //new LoadGigsTask().execute(currentPage + 1);
                loading = true;

                String url = "";


                //String url = app.Domain + "/getProducts.json?category_id=" + category_id;
                url = "url-of-api" + "&page=" + currentPage;

                //Log.v("product url",url);

                StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                        new Response.Listener() {
                            @Override
                            public void onResponse(String response) {

                                Integer newitems = 0;

                                JSONObject jsonObject = null;
                                try {
                                    jsonObject = new JSONObject(response);

                                    JSONObject results = jsonObject.getJSONObject("results");
                                    JSONArray data = results.getJSONArray("data");

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

                                        String id = jo.getString("id");
                                        String product_name = jo.getString("product_name");
                                        String product_image = jo.getString("product_image");
                                        String prod_desc = jo.getString("prod_desc");
                                        products.add(new Product(id, product_name, prod_desc, product_image))
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                                if (newitems > 0) {
                                    gridAdapter.notifyDataSetChanged();
                                }


                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.v("res", "api not wokred" + error);
                    }
                });


                stringRequest.setRetryPolicy(new DefaultRetryPolicy(0,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                queue = Volley.newRequestQueue(context);
                queue.add(stringRequest);
            }


            //Log.v("currentPage",Integer.toString(currentPage));
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }
    }

Below is full activity code for reference.


public class MyProductsActivity extends AppCompatActivity   {

    

    Context context;
    Activity activity;
    
    RequestQueue queue;

    

    ProductListViewAdapterAdapter gridAdapter;
    public ArrayList products = new ArrayList<>();

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

        activity = this;

        context = getApplicationContext();

        String url  = "url-of-api";

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener() {
                    @Override
                    public void onResponse(String response) {


                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(response);

                            JSONObject results = jsonObject.getJSONObject("results");
                            JSONArray data = results.getJSONArray("data");

                            for (int i = 0; i < data.length(); i++) {
                                String id = jo.getString("id");
                                String product_name = jo.getString("product_name");
                                String product_image = jo.getString("product_image");
                                String prod_desc = jo.getString("prod_desc");
                                products.add(new Product(id, product_name, prod_desc, product_image))
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }



                        GridView gridView = (GridView) findViewById(R.id.gridView);

                        gridAdapter = new ProductListViewAdapterAdapter(MyProductsActivity.this, R.layout.my_products_list_layout, products);

                        gridView.setAdapter(gridAdapter);


                        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            public void onItemClick(AdapterView parent, View v, int position, long id) {
                                
                                //code execute when user click on any grid column

                            }
                        });

                        gridView.setOnScrollListener(new EndlessScrollListener());

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("Api Error", "Api Not working " + error);
            }
        });


        stringRequest.setRetryPolicy(new DefaultRetryPolicy(0,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue = Volley.newRequestQueue(getApplicationContext());
        queue.add(stringRequest);
    }


    public class EndlessScrollListener implements AbsListView.OnScrollListener {

        private int visibleThreshold = 6;
        private int currentPage = 1;
        private int previousTotal = 0;
        private boolean loading = true;

        public EndlessScrollListener() {
        }

        public EndlessScrollListener(int visibleThreshold) {
            this.visibleThreshold = visibleThreshold;
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {
            if (loading) {
                if (totalItemCount > previousTotal) {
                    loading = false;
                    previousTotal = totalItemCount;
                    currentPage++;
                }
            }

            //Log.v("firstVisibleItem",Integer.toString(firstVisibleItem));
            //Log.v("visibleItemCount",Integer.toString(visibleItemCount));
            //Log.v("totalItemCount",Integer.toString(totalItemCount));

            Boolean c = (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold);
            //Log.v("result", String.valueOf(c));

            if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
                // I load the next page of gigs using a background task,
                // but you can call any function here.


                //new LoadGigsTask().execute(currentPage + 1);
                loading = true;

                String url = "";


                //String url = app.Domain + "/getProducts.json?category_id=" + category_id;
                url = "url-of-api" + "&page=" + currentPage;

                //Log.v("product url",url);

                StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                        new Response.Listener() {
                            @Override
                            public void onResponse(String response) {

                                Integer newitems = 0;

                                JSONObject jsonObject = null;
                                try {
                                    jsonObject = new JSONObject(response);

                                    JSONObject results = jsonObject.getJSONObject("results");
                                    JSONArray data = results.getJSONArray("data");

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

                                        String id = jo.getString("id");
                                        String product_name = jo.getString("product_name");
                                        String product_image = jo.getString("product_image");
                                        String prod_desc = jo.getString("prod_desc");
                                        products.add(new Product(id, product_name, prod_desc, product_image))
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                                if (newitems > 0) {
                                    gridAdapter.notifyDataSetChanged();
                                }


                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.v("res", "api not wokred" + error);
                    }
                });


                stringRequest.setRetryPolicy(new DefaultRetryPolicy(0,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                queue = Volley.newRequestQueue(context);
                queue.add(stringRequest);
            }


            //Log.v("currentPage",Integer.toString(currentPage));
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }
    }


}

You can use this code as it is by doing some small changes. To implement gridview we need more files. if you have confusion using this example, Please read previous article, Link has been given in above paragraph.

Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

fifteen + thirteen =