0

i am making new and my first app with android studio , I am noob so don't know much about it, i made app with retrofit and Wordpress, i have displayed first 10 posts successfully but i don't know how to load more posts on scroll , please help, this is my Main Activity , i have Implemented EndlessRecyclerOnScrollListener.java class but don't know what should i write there

OnCreate:

 super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    list = new ArrayList<Model>();
    progressBar = (ProgressBar) findViewById(R.id.progressbar);
    adapter = new RecyclerViewAdapter(list,this);
    mLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(mLayoutManager);
    getRetrofit();
    recyclerView.setAdapter(adapter);


    scrollListener = new EndlessRecyclerOnScrollListener(mLayoutManager) {
        @Override
        public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {



        }
    };
    // Adds the scroll listener to RecyclerView
    recyclerView.addOnScrollListener(scrollListener);


    recyclerView.post(new Runnable() {
        @Override
        public void run() {
            // Notify adapter with appropriate notify methods

            adapter.notifyItemRangeInserted(curSize, list.size() - 1);
        }
    });

}

this is my retrofit :

public void getRetrofit(){
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseURL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RetrofitArrayApi service = retrofit.create(RetrofitArrayApi.class);
    String yourURl = yourURL.replace(baseURL,"");
    Call<List<WPPost>>  call = service.getPostInfo( yourURl);
    call.enqueue(new Callback<List<WPPost>>() {
        @Override
        public void onResponse(Call<List<WPPost>> call, Response<List<WPPost>> response) {
            Log.e("mainactivyt", " response "+ response.body());
            mListPost = response.body();
            progressBar.setVisibility(View.GONE);
            if (response.body() != null) {


                for (int i = 0; i < response.body().size(); i++ ) {


                    Log.e("size", list.size() + "");


                    System.out.println("The shortest word i is:" + i );




                    Log.e("main ", " title " + response.body().get(i).getTitle().getRendered() + " " +
                            response.body().get(i).getId());
                    String tempdetails = response.body().get(i).getExcerpt().getRendered().toString();
                    tempdetails = tempdetails.replace("<p>", "");
                    tempdetails = tempdetails.replace("</p>", "");
                    tempdetails = tempdetails.replace("[&hellip;]", "");
                    list.add(new Model(Model.IMAGE_TYPE, response.body().get(i).getTitle().getRendered(),
                            tempdetails,
                            response.body().get(i).getImages().getMedium()));





                }




                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.GONE);
            }


            adapter.notifyDataSetChanged();

        }
        @Override
        public void onFailure(Call<List<WPPost>> call, Throwable t) {
        }
    });
}

Retrofit Api

public interface RetrofitArrayApi {


@GET("android/wp-json/wp/v2/posts")
Call<List<WPPost>> getPostInfo();

@GET("paged/list/endpoint")
static Call<WPPost.PagedList<Object>> getPagedList(@Query("page") int page) {
    return null;
}

In WPPost.java

public class PagedList<T> {

    private int page = 0;
    private List<T> results = new ArrayList<>();
    private int totalResults = 0;
    private int totalPages = 0;

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public List<T> getResults() {
        return results;
    }
    public void setResults(List<T> results) {
        this.results = results;
    }

    public int getTotalResults() {
        return totalResults;
    }

    public void setTotalResults(int totalResults) {
        this.totalResults = totalResults;
    }

    public int getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(int totalPages) {
        this.totalPages = totalPages;
    }
}

Adapter

 private ArrayList<Model> dataset;
private Context mContext;
int total_types;

private List<Object> list;




public RecyclerViewAdapter(ArrayList<Model> mlist, Context context) {
    this.dataset = mlist;
    this.mContext = context;
    total_types = dataset.size();
}

public void setList(List<Object> list) {
    this.list = list;
    notifyDataSetChanged();
}

public void addAll(List<Object> newList) {
    int lastIndex = list.size() - 1;
    list.addAll(newList);
    notifyItemRangeInserted(lastIndex, newList.size());
}

MainActivity

super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mIsLoading = false;
    mIsLastPage = false;

    final int pageSize = 20;
    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    list = new ArrayList<Model>();
    progressBar = (ProgressBar) findViewById(R.id.progressbar);
    adapter = new RecyclerViewAdapter(list,this);
    mLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);

    recyclerView.setLayoutManager(mLayoutManager);
    list = new ArrayList<Model>();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseURL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RetrofitArrayApi service = retrofit.create(RetrofitArrayApi.class);
    Call<List<WPPost>>  call = service.getPostInfo();
    call.enqueue(new Callback<List<WPPost>>() {
                     @Override
                     public void onResponse(Call<List<WPPost>> call, Response<List<WPPost>> response) {
                         Log.e("mainactivyt", " response " + response.body());
                         mListPost = response.body();
                         progressBar.setVisibility(View.GONE);
                         if (response.body() != null) {
                             for (int i = 0; i < response.body().size(); i++) {
                                 Log.e("size", list.size() + "");
                                 System.out.println("The shortest word i is:" + i);
                                 Log.e("main ", " title " + response.body().get(i).getTitle().getRendered() + " " +
                                         response.body().get(i).getId());
                                 String tempdetails = response.body().get(i).getExcerpt().getRendered().toString();
                                 tempdetails = tempdetails.replace("<p>", "");
                                 tempdetails = tempdetails.replace("</p>", "");
                                 tempdetails = tempdetails.replace("[&hellip;]", "");
                                 list.add(new Model(Model.IMAGE_TYPE, response.body().get(i).getTitle().getRendered(),
                                         tempdetails,
                                         response.body().get(i).getImages().getMedium()));
                             }
                             progressBar.setVisibility(View.GONE);
                         } else {
                             progressBar.setVisibility(View.GONE);
                         }
                         adapter.notifyDataSetChanged();

                     }

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

                     }

                 });


    recyclerView.addOnScrollListener(new  RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            // number of visible items
            int visibleItemCount = mLayoutManager.getChildCount();
            // number of items in layout
            int totalItemCount = mLayoutManager.getItemCount();
            // the position of first visible item
            int firstVisibleItemPosition = mLayoutManager.findFirstVisibleItemPosition();

            boolean isNotLoadingAndNotLastPage = !mIsLoading && !mIsLastPage;
            // flag if number of visible items is at the last
            boolean isAtLastItem = firstVisibleItemPosition + visibleItemCount >= totalItemCount;
            // validate non negative values
            boolean isValidFirstItem = firstVisibleItemPosition >= 0;
            // validate total items are more than possible visible items
            boolean totalIsMoreThanVisible = totalItemCount >= pageSize;
            // flag to know whether to load more
            boolean shouldLoadMore = isValidFirstItem && isAtLastItem && totalIsMoreThanVisible && isNotLoadingAndNotLastPage;

            if (shouldLoadMore) loadMoreItems(false);
        }
    });

    // load the first page

    loadMoreItems(true);

    adapter = new RecyclerViewAdapter( list, MainActivity.this);
    recyclerView.setAdapter(adapter);


}



private void loadMoreItems(boolean isFirstPage) {
    // change loading state
    mIsLoading = true;
    mCurrentPage = mCurrentPage + 1;

    // update recycler adapter with next page
    RetrofitArrayApi.getPagedList(mCurrentPage).enqueue(new Callback<WPPost.PagedList<Object>>() {
        @Override
        public void onResponse(Call<WPPost.PagedList<Object>> call, Response<WPPost.PagedList<Object>> response) {
            WPPost.PagedList<Object> result = response.body();

            if (result == null) return;
            else if (!isFirstPage) adapter.addAll(result.getResults());
            else adapter.setList(result.getResults());

            mIsLoading = false;
            mIsLastPage = mCurrentPage == result.getTotalPages();
        }

        @Override
        public void onFailure(Call<WPPost.PagedList<Object>> call, Throwable t) {
            Log.e("SomeActivity", t.getMessage());
        }
    });
}

i have searched lot for past week , but still not working, please help....

0 Answers0