java-RecycleView分页末尾没有添加新项目?

我正在通过Web服务从服务器获取数据并在回收视图中显示.每个请求都从服务器获取5个项目.我调试了代码,并检查了当我滚动到recycleview的末尾时,是否从服务器获取了新数据,但未在recycleview的末尾添加新数据.我该如何解决?

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

解决方法:

我认为您每次调用getTimeLineData()时都会创建一个新的项目列表:

timeLineItems = new ArrayList<>();

首先检查您是否已有列表:

if (timeLineItems == null) {
    timeLineItems = new ArrayList<>();
}
上一篇:android-以编程方式选择AutoCompleteTextView项目


下一篇:我在项目中使用带有PHP的工作单位设计模式