Java – RecycleView Pagination doesn’t add a new item at the end?

RecycleView Pagination doesn’t add a new item at the end?… here is a solution to the problem.

RecycleView Pagination doesn’t add a new item at the end?

I get data from the server through a web service and display it in the Reclamation View. I get 5 items from the server per request. I debug my code and check that when I scroll to the end of the recycleview, new data is getting from the server, but it is not added to the end of the recycleview. How do I fix it?

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timeline);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

listView = (RecyclerView) findViewById(R.id.listview);
        listView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        listView.setLayoutManager(layoutManager);

Adding an scroll change listener to recyclerview
        listView.setOnScrollChangeListener(this);

 Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

cd = new ConnectionDetector(this);
        isInternetPresent = cd.isConnectingToInternet();

db = new SQLiteHandler(this);

 session manager
        session = new SessionManager(this);

/*pref = getApplicationContext().getSharedPreferences("MayahudiPref", 0);
        editor = pref.edit(); */

 Fetching user details from sqlite
        HashMap<String, String> user = db.getUserDetails();
        id = user.get("id");
        token = user.get("token");

getData();

adapter = new TimeLineListAdapter(timeLineItems, this);
        listView.setAdapter(adapter);
    }

public void getTimeLineData(final String token, final String page) {

timeLineItems = new ArrayList<>();

String tag_string_req = "req_register";
             making fresh volley request and getting json
            StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.timeline, new Response.Listener<String>() {

@Override
                public void onResponse(String response) {
                    VolleyLog.d(TAG, "Response: " + response.toString());
                    if (response != null) {
                        try {
                            JSONObject jObj = new JSONObject(response);
                            boolean error = jObj.getBoolean("status");
                            String message = jObj.getString("message");
                            if(error){
                                totalPages = jObj.getInt("totalPages");
                                pageCount = jObj.getInt("page");

int limit = jObj.getInt("limit");
                                parseJsonFeed(response);
                            }

}catch (Exception e){

}

}
                }
            }, new Response.ErrorListener() {

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

@Override
                protected Map<String, String> getParams() {
                     Posting params to register url
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("my_token", token);
                    params.put("page", page);
                    params.put("limit", "5");

return params;
                }
            };

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

}

private void parseJsonFeed(String response) {
        try {
            JSONObject jsonObj = new JSONObject(response);
            JSONArray feedArray = jsonObj.getJSONArray("data");

for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);

TimeLineItem item = new TimeLineItem();
                item.setId(feedObj.getInt("id"));
                item.setName(feedObj.getString("name"));
                item.setLname(feedObj.getString("lname"));

 Image might be null sometimes
                String image = feedObj.isNull("image") ? null : feedObj
                        .getString("image");
                item.setImge(image);
                item.setStatus(feedObj.getString("story_text"));
                item.setProfilePic(feedObj.getString("profile_pic"));
                item.setTimeStamp(feedObj.getString("time_stamp"));
                item.setIsLike(feedObj.getInt("is_like"));
                item.setTotalLikes(feedObj.getString("total_likes"));
                item.setTotalComment(feedObj.getString("total_comments"));

/*// url might be null sometimes
                String feedUrl = feedObj.isNull("url") ? null : feedObj
                        .getString("url");
                item.setUrl(feedUrl); */

timeLineItems.add(item);
            }

 notify data changes to list adapater
            adapter.notifyDataSetChanged();

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

This method will get data from the web API
    private void getData() {
        Adding the method to the queue by calling the method getDataFromServer
        getTimeLineData(token , String.valueOf(requestCount));
        Incrementing the request counter
        requestCount++;
    }

This method would check that the recyclerview scroll has reached the bottom or not
    private boolean isLastItemDisplaying(RecyclerView recyclerView) {
        if (recyclerView.getAdapter().getItemCount() != 0) {
            int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
            if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)

return true;
        }
        return false;
    }

@Override
    public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
        Ifscrolled at last then
        if (isLastItemDisplaying(listView)) {
            Calling the method getdata again
            getData();
        }
    }

Solution

I think you create a new list of items every time you call getTimeLineData():

timeLineItems = new ArrayList<>();

First check if you already have a list:

if (timeLineItems == null) {
    timeLineItems = new ArrayList<>();
}

Related Problems and Solutions