Skip to content Skip to sidebar Skip to footer

Is There Any Way To Load 5 - 10 Items In Recyclerview At A Time Instead Of 50k?

I have to show a list of airports of the world, and user has to choose one of them. So I have made a recyclerview: RecyclerView recyclerView = (RecyclerView)rootView.findViewBy

Solution 1:

Solution 2:

You can use pagination concept.

Pagination:It is a process of dividing a document into multiple pages.

I used pagination as below:

recyclerView.addOnScrollListener(newRecyclerView.OnScrollListener() {
        @OverridepublicvoidonScrolled(RecyclerView recyclerView, int dx, int dy) {
            LinearLayoutManager linearLayoutManager= (LinearLayoutManager) recyclerView.getLayoutManager();


    /*countToShowLoadButton here is total number of items available to 
    *user after no. of page requests. So when total visible item would 
    *reach to the end (i.e. countToShowLoadButton-3) then a "load more"
    *button would appear and it will call a new request loadMoreData
    */if(linearLayoutManager.findLastVisibleItemPosition() > countToShowLoadButton-3 && currentPageNumber < totalPageNumber){
                loadMoreButton.setVisibility(View.VISIBLE);
                loadMoreButton.setEnabled(true);
            }
            super.onScrolled(recyclerView, dx, dy);
        }
    });

loadMoreData:

public void loadMoreData(View view){
    getAllData(currentPageNumber+1);
}

getAllData:

publicvoidgetAllData(int pageNo){

    progressBar.setVisibility(View.VISIBLE);

    final String key = sharedPreferences.getString("Auth_key",null);

    String pageNumber = String.valueOf(pageNo);

    checkInternet = newInternetConnectivityChecker(getApplicationContext());

    if(checkInternet.isOnline()) {

        StringRequest stringRequest = newStringRequest(Request.Method.GET,
                URL_string.api_url +"?"+pageNumber,
                newResponse.Listener<String>() {
                    @OverridepublicvoidonResponse(String response) {
                        Log.i("Result", "Success \n" + response);

                        try {
                            JSONObject responseJSON = newJSONObject(response);

                            JSONArray dataPart = responseJSON.getJSONArray("data");
                            JSONObject metaPart = responseJSON.getJSONObject("meta").getJSONObject("pagination");

//Here it updates all the variable so that when user clicks on "load more" // button again then it loads the data from new page

                            currentPageNumber = metaPart.getInt("current_page");
                            totalPageNumber = metaPart.getInt("total_pages");
                            totalNumberOfData = metaPart.getInt("total");
                            perPageItems = metaPart.getInt("per_page");
                            dataAtShownPage = metaPart.getInt("count");
                            countToShowLoadButton = perPageItems * currentPageNumber;


//Here it adds new data to the shown page of the appprepareValueWithServerData(dataPart,dataAtShownPage);


                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(),noNetConnMessage,Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    }
                }, newResponse.ErrorListener() {
            @OverridepublicvoidonErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(),noNetConnMessage,Toast.LENGTH_LONG).show();
            }
        }) {

            @OverridepublicMap<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> header = newHashMap<>();
                header.put("Authorization", "Bearer " + key);
                return header;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        stringRequest.setRetryPolicy(newDefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(stringRequest);

        if(stringRequest.getTimeoutMs() > DefaultRetryPolicy.DEFAULT_TIMEOUT_MS*2){
            requestQueue.stop();
            Toast.makeText(getApplicationContext(),noNetConnMessage,Toast.LENGTH_LONG).show();
            progressBar.setVisibility(View.INVISIBLE);
        }

    } else {
        Toast.makeText(getApplicationContext(),"Please Check Internet Connection",Toast.LENGTH_LONG).show();
    }

}

PrepareValueWithServerData:

publicvoidprepareValueWithServerData(JSONArray data, int count){

    progressBar.setVisibility(View.INVISIBLE);

    for(int i=0; i<count; i++){
        try {
            JSONObjectsingleItem= data.getJSONObject(i);
            item_detailsa=newitem_details(details_1,details_2,..);
            list.add(a);


 //notifying adapter that data has been changed in the list
            adapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Note: Server would have to return data according to pages counts i.e. pagination concept will be used in server-side programming so that it doesn't return 50K data at once, else it should return just 10-20 or so data according to the requested page. It would make your app work faster.

Post a Comment for "Is There Any Way To Load 5 - 10 Items In Recyclerview At A Time Instead Of 50k?"