RecycleView pagination doesn't add new item at the end?

I am fetching data from the server via a web service and showing it in view mode. Each request I receive 5 items from the server. I am debugging my code and have verified that when I scroll to the end of the recycleview, new data comes in from the server, but not appended to the end of the recycleview. How can I solve this?

@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();
        }
    }

      

+3


source to share


3 answers


I think you are creating a list of new items every time you call getTimeLineData()

:

timeLineItems = new ArrayList<>();

      



First check if you have a list:

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

      

+3


source


RecylerView article_list;


article_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            visibleitemcount = linearLayoutManager.getChildCount();
            total_itemcount = linearLayoutManager.getItemCount();
            pastVisiblecount = linearLayoutManager.findFirstVisibleItemPosition();
            Log.d(TAG, "Total : " + total_itemcount + "Visible : " + visibleitemcount + "Past : " + pastVisiblecount);
            if (loading) {
                if (visibleitemcount + pastVisiblecount >= total_itemcount) {
                    loading = false;
                    getHealthyLivingfromUrl(5, 0);
                }
            }
        }
    });


private void getHealthyLivingfromUrl(int limit, int offset) {

            //get the data code
       article_list.setAdapter(articleAdapter);
                        if (total_itemcount!=0 && total_itemcount > visibleitemcount) {
                            linearLayoutManager.setSmoothScrollbarEnabled(true);
                            linearLayoutManager.scrollToPosition(total_itemcount-visibleitemcount);
                        }
                        loading = true;

}

      



0


source


Why are you using POST method to get data? Every time you get data you create a new array, onCreate you assign an array to the adapter. Then you create one, but don't assign. I think you should create in the adapter class, addItems (List items) methods, and every time you get data you use this method (inside this method you can change the notifi data). All this.

0


source







All Articles