通过获取api的数据无休止地滚动recyclelerview

时间:2018-04-19 05:49:34

标签: android android-recyclerview retrofit2

我有一个api,每页包含10个数据,现在我想加载下一页的其他10个数据,同时我向下滚动回收器视图但是我在加载下一页数据时遇到一些问题,下一页数据没有&加载,如果我能得到一些帮助,那就太棒了。 我的EndlessScroll java代码:

public abstract class EndlessRecyclerViewScrollListener extends RecyclerView.OnScrollListener {
    // The minimum amount of items to have below your current scroll position
    // before loading more.
    private int visibleThreshold = 10;
    // The current offset index of data you have loaded
    private int currentPage = 0;
    // The total number of items in the dataset after the last load
    private int previousTotalItemCount = 0;
    // True if we are still waiting for the last set of data to load.
    private boolean loading = true;
    // Sets the starting page index
    private int startingPageIndex = 0;

    RecyclerView.LayoutManager mLayoutManager;

    public EndlessRecyclerViewScrollListener(LinearLayoutManager layoutManager) {
        this.mLayoutManager = layoutManager;
    }

    public EndlessRecyclerViewScrollListener(GridLayoutManager layoutManager) {
        this.mLayoutManager = layoutManager;
        visibleThreshold = visibleThreshold * layoutManager.getSpanCount();
    }

    public EndlessRecyclerViewScrollListener(StaggeredGridLayoutManager layoutManager) {
        this.mLayoutManager = layoutManager;
        visibleThreshold = visibleThreshold * layoutManager.getSpanCount();
    }

    public int getLastVisibleItem(int[] lastVisibleItemPositions) {
        int maxSize = 0;
        for (int i = 0; i < lastVisibleItemPositions.length; i++) {
            if (i == 0) {
                maxSize = lastVisibleItemPositions[i];
            }
            else if (lastVisibleItemPositions[i] > maxSize) {
                maxSize = lastVisibleItemPositions[i];
            }
        }
        return maxSize;
    }

    // This happens many times a second during a scroll, so be wary of the code you place here.
    // We are given a few useful parameters to help us work out if we need to load some more data,
    // but first we check if we are waiting for the previous load to finish.
    @Override
    public void onScrolled(RecyclerView view, int dx, int dy) {
        int lastVisibleItemPosition = 0;
        int totalItemCount = mLayoutManager.getItemCount();

        if (mLayoutManager instanceof StaggeredGridLayoutManager) {
            int[] lastVisibleItemPositions = ((StaggeredGridLayoutManager) mLayoutManager).findLastVisibleItemPositions(null);
            // get maximum element within the list
            lastVisibleItemPosition = getLastVisibleItem(lastVisibleItemPositions);
        } else if (mLayoutManager instanceof GridLayoutManager) {
            lastVisibleItemPosition = ((GridLayoutManager) mLayoutManager).findLastVisibleItemPosition();
        }
        else if (mLayoutManager instanceof LinearLayoutManager) {
            lastVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
        }

        // If the total item count is zero and the previous isn't, assume the
        // list is invalidated and should be reset back to initial state
        if (totalItemCount < previousTotalItemCount) {
            this.currentPage = this.startingPageIndex;
            this.previousTotalItemCount = totalItemCount;
            if (totalItemCount == 0) {
                this.loading = true;
            }
        }
        // If it’s still loading, we check to see if the dataset count has
        // changed, if so we conclude it has finished loading and update the current page
        // number and total item count.
        if (loading && (totalItemCount > previousTotalItemCount)) {
            loading = false;
            previousTotalItemCount = totalItemCount;
        }

        // If it isn’t currently loading, we check to see if we have breached
        // the visibleThreshold and need to reload more data.
        // If we do need to reload some more data, we execute onLoadMore to fetch the data.
        // threshold should reflect how many total columns there are too
        if (!loading && (lastVisibleItemPosition + visibleThreshold) > totalItemCount) {
            currentPage++;
            onLoadMore(currentPage, totalItemCount, view);
            loading = true;
        }
    }

    // Call this method whenever performing new searches
    public void resetState() {
        this.currentPage = this.startingPageIndex;
        this.previousTotalItemCount = 0;
        this.loading = true;
    }

    // Defines the process for actually loading more data based on page
    public abstract void onLoadMore(int page, int totalItemsCount, RecyclerView view);

}

我的片段,我想使用无尽的回收者视图:

public class BlankFragment extends DialogFragment {
    public Session session;
    private RecyclerView categoryRecyclerView, property_recycler;
    private PropertyAdapter propertyAdapter;
    private EndlessRecyclerViewScrollListener scrollListener;
    private ApiInterface apiInterface;
    private Datum datum;
    private String next_page_url = null;

    public BlankFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_blank, container, false);
        apiInterface = ApiClient.getClient().create(ApiInterface.class);
        property_recycler = view.findViewById(R.id.viewAllHotRc);
        final RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        property_recycler.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        property_recycler.setHasFixedSize(true);
        property_recycler.setItemAnimator(new DefaultItemAnimator());
        scrollListener = new EndlessRecyclerViewScrollListener((LinearLayoutManager) mLayoutManager) {
            @Override
            public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
                // Triggered only when new data needs to be appended to the list
                // Add whatever code is needed to append new items to the bottom of the list
                if (next_page_url != null) {
                    getNextPageData(next_page_url);
                    next_page_url = null;
                }
            }

        };
        property_recycler.addOnScrollListener(scrollListener);

        session = new Session(getContext());
        Call<Datum> propertyCall = apiInterface.getAllProp(session.getAccessToken());
        propertyCall.enqueue(new Callback<Datum>() {
            @Override
            public void onResponse(Call<Datum> call, Response<Datum> response) {
                if (response.code() == 200) {
                    datum = response.body();
                    final List<Property> propertyList = datum.getPropertyList();
                    propertyAdapter = new PropertyAdapter(propertyList, getContext());
                    property_recycler.setAdapter(propertyAdapter);

                    String pagingObject = datum.getNextPageUrl();
                    Log.d(TAG, "onResponse: "+pagingObject);

                    if (pagingObject != null) {
                        next_page_url = pagingObject;
                        Log.d(TAG, "NEXTPAGE: "+next_page_url);

                    } else if (pagingObject== null) {
                        next_page_url = null;
                    }

                }
            }

            @Override
            public void onFailure(Call<Datum> call, Throwable t) {
                if (!call.isCanceled()) {
                    t.printStackTrace();
                }
            }
        });
        return view;
    }
    void getNextPageData(String nextUrl) {

        Call<Datum> callNextPageData = apiInterface.getNxt(session.getAccessToken());
        callNextPageData.enqueue(new Callback<Datum>() {
            @Override
            public void onResponse(Call<Datum> call, Response<Datum> response) {
                datum = response.body();
                final List<Property> propertyList = datum.getPropertyList();
                propertyAdapter = new PropertyAdapter(propertyList, getContext());
                property_recycler.setAdapter(propertyAdapter);

                String pagingObject = datum.getNextPageUrl();
                Log.d(TAG, "onResponse: "+pagingObject);

                    if (pagingObject== null) {
//                        getNextPageData(pagingObject.getString("next"));
                        next_page_url = pagingObject;
                    } else if (pagingObject == null) {
                        next_page_url = null;
                    }



            }

            @Override
            public void onFailure(Call<Datum> call, Throwable t) {

            }
        });
    }

我的Api模型:

public class Datum {

    @SerializedName("current_page")
    @Expose
    private int currentPage;
    @SerializedName("data")
    @Expose
    private List<Property> propertyList = null;
    @SerializedName("first_page_url")
    @Expose
    private String firstPageUrl;
    @SerializedName("from")
    @Expose
    private int from;
    @SerializedName("next_page_url")
    @Expose
    private String nextPageUrl;
    @SerializedName("path")
    @Expose
    private String path;
    @SerializedName("per_page")
    @Expose
    private int perPage;
    @SerializedName("prev_page_url")
    @Expose
    private String prevPageUrl;
    @SerializedName("to")
    @Expose
    private int to;

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public List<Property> getPropertyList() {
        return propertyList;
    }

    public void setPropertyList(List<Property> propertyList) {
        this.propertyList = propertyList;
    }

    public String getFirstPageUrl() {
        return firstPageUrl;
    }

    public void setFirstPageUrl(String firstPageUrl) {
        this.firstPageUrl = firstPageUrl;
    }

    public int getFrom() {
        return from;
    }

    public void setFrom(int from) {
        this.from = from;
    }

    public String getNextPageUrl() {
        return nextPageUrl;
    }

    public void setNextPageUrl(String nextPageUrl) {
        this.nextPageUrl = nextPageUrl;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public int getPerPage() {
        return perPage;
    }

    public void setPerPage(int perPage) {
        this.perPage = perPage;
    }

    public String getPrevPageUrl() {
        return prevPageUrl;
    }

    public void setPrevPageUrl(String prevPageUrl) {
        this.prevPageUrl = prevPageUrl;
    }

我的界面:

@ GET(&#34; / API /属性&#34) 调用getAllProp(@Header(&#34; Authorization&#34;)String token);

@ GET(&#34; / API /属性&#34) 调用getNxt(@Header(&#34; Authorization&#34;)String token);

0 个答案:

没有答案