This question already has answers here:
How to implement endless list with RecyclerView?
(36 answers)
Closed 5 years ago.
I have a REST method that returns JSON object,the JSON file size almost weighs 7MB and has almost 4600 JSON object. I am unable to parse the entire data at a time into recyclerView as it causes OutOfMemory Exception.
I tried to implement it in 2 ways. One is using http://loopj.com/android-async-http/ but this method is not feasible to large chunk of data. The second method was done using GSON and Volley. Using this method i am able to get the response much faster from the REST method but i'm unable to populate it into recyclerView. Please do check out the code that i used.
The problem that i'm facing here is that recyclerview shows null values for ROLL_NUM, CURRENT_CLASS, STUDENT_NAME
sample JSON response: {"RestResult":[{""ROLL_NUM":7071,"CURRENT_CLASS":"Grade LKG C","STUDENT_NAME":"A. VEDANJALI AKULA VEDANJALI"}
ListItem.class
String STUDENT_NAME;
String CURRENT_CLASS;
String ROLL_NUMBER;
public String getSTUDENT_NAME() {
return STUDENT_NAME;
}
public String getCURRENT_CLASS() {
return CURRENT_CLASS;
}
public String getROLL_NUMBER() {
return ROLL_NUMBER;
}
public GetSet(String STUDENT_NAME, String CURRENT_CLASS, String ROLL_NUMBER) {
this.STUDENT_NAME = STUDENT_NAME;
this.CURRENT_CLASS = CURRENT_CLASS;
this.ROLL_NUMBER = ROLL_NUMBER;
}
RecyclerAdapter.class
private List<GetSet> itemList;
private Context context;
public RecyclerViewAdapter(Context context, List<GetSet> itemList) {
this.itemList = itemList;
this.context = context;
}
#Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, null);
RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(RecyclerViewHolders holder, int position) {
holder.songTitle.setText("Student Name: " + itemList.get(position).getSTUDENT_NAME());
holder.songYear.setText("Current Class: " + itemList.get(position).getCURRENT_CLASS());
holder.songAuthor.setText("Roll Number: " + itemList.get(position).getROLL_NUMBER());
}
#Override
public int getItemCount() {
return this.itemList.size();
}
ActivityMain.class
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://webservices.educatemax.com/vidyaMandir.svc/RetrieveStudentsList?iGroupID=1&iSchoolID=1&iBoardID=1&iClassID=1";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.hide();
Log.d(TAG, "Response " + response);
GsonBuilder builder = new GsonBuilder();
Gson mGson = builder.create();
List<GetSet> posts = new ArrayList<>();
posts = Arrays.asList(mGson.fromJson(response, GetSet.class));
adapter = new RecyclerViewAdapter(ActivityMain.this, posts);
recyclerView.setAdapter(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error " + error.getMessage());
}
});
queue.add(stringRequest);
you can use an scroll listener like this :
public abstract class RecyclerViewOnScrollListener extends RecyclerView.OnScrollListener {
private final int mVisibleThreshold = 1;
private int mPreviousTotal = 0;
private boolean isLoading = true;
private int mFirstVisibleItem;
private int mVisibleItemsCount;
private int mTotalItemsCount;
private int mCurrentPage = 0;
private LinearLayoutManager mLayoutManager;
public RecyclerViewOnScrollListener(LinearLayoutManager manager) {
this.mLayoutManager = manager;
}
public void init() {
this.mPreviousTotal = 0;
this.isLoading = true;
this.mCurrentPage = 0;
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
mVisibleItemsCount = recyclerView.getChildCount();
mTotalItemsCount = mLayoutManager.getItemCount();
mFirstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
if (isLoading && mTotalItemsCount > mPreviousTotal) {
isLoading = false;
mPreviousTotal = mTotalItemsCount;
}
if (!isLoading && (mTotalItemsCount - mVisibleItemsCount) <= (mFirstVisibleItem + mVisibleThreshold)) {
mCurrentPage = mCurrentPage + 10;
onLoadMore(mCurrentPage);
isLoading = true;
}
}
public abstract void onLoadMore(int currentPage);
}
and in your Activity of Fragment(anyWhere you have your recyclerView):
mRecyclerOnScrollListener = new RecyclerViewOnScrollListener(new GridLayoutManager(MyActivity.this, getResources().getInteger(R.integer.num_columns))) {
#Override
public void onLoadMore(int currentPage) {
//here you can manage content and add to your adaprer
}
};
Related
I haven't found yet the proper examples of how to make an app load more items from Retrofit onResponse while scrolling down the RecyclerView.
Here is how I'm loading my fist 20 items:
List<ModelPartners> model = new ArrayList<>();
Call<ResponsePartners> call = ApiClient.getRetrofit().getPartnerList(params);
call.enqueue(this);
My RecyclerView
PartnersAdapter adapter = new PartnersAdapter(getContext(), recyclerView, model);
recyclerView.setAdapter(adapter);
And here is my Retrofit onResponse:
#Override
public void onResponse(Call<ResponsePartners> call, Response<ResponsePartners> response) {
if (getActivity() != null && response.isSuccessful()) {
List<ModelPartners> body = response.body().getData();
//Rest of the code to add body to my Adapter and notifyDataSetChanged
}
}
My Problem is, every time I add the method to load more items on scroll, onResponse keeps loading non-stop till the last page. Even if I have put set loading to false.
Can someone please show how to properly use pagination in Retrofit? What libraries you used with Retrofit or show me how you did it your way? Thank you in advance
You need three things to achieve this, you need:
You need an onscroll listener for the recycler view.
You need a method to add new items to the recycler adapter
You need to call your paginated endpoint
Assuming you have a model like this from the server
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;
}
}
Your OnScroll Listener: -
In your activity this is what you would have, so add the second method to your activity
public void onCreate(Bundle savedInstance) {
// setup your view components
// ...
// get the layout manager
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
// rest endpoint
apiEndpoint = retrofit.create(RetrofitEndpoint.class);
// initialise loading state
mIsLoading = false;
mIsLastPage = false;
// amount of items you want to load per page
final int pageSize = 20;
// set up scroll listener
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 = layoutManager.getChildCount();
// number of items in layout
int totalItemCount = layoutManager.getItemCount();
// the position of first visible item
int firstVisibleItemPosition = layoutManager.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);
}
private void loadMoreItems(boolean isFirstPage) {
// change loading state
mIsLoading = true;
mCurrentPage = mCurrentPage + 1;
// update recycler adapter with next page
apiEndpoint.getPagedList(mCurrentPage).enqueue(new Callback<PagedList<Object>>() {
#Override
public void onResponse(Call<PagedList<Object>> call, Response<PagedList<Object>> response) {
PagedList<Object> result = response.body();
if (result == null) return;
else if (!isFirstPage) mAdapter.addAll(result.getResults());
else mAdapter.setList(result.getResults());
mIsLoading = false;
mIsLastPage = mCurrentPage == result.getTotalPages();
}
#Override
public void onFailure(Call<PagedList<Object>> call, Throwable t) {
Log.e("SomeActivity", t.getMessage());
}
});
}
Recycler Adapter: -
For the recycler adapter all you need is to add a method that adds items to its list, as below
public class SomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Object> list;
// .. other overridden members
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());
}
}
Then finally your retrofit interface that takes the page, as below:
interface RetrofitEndpoint {
#GET("paged/list/endpoint")
Call<PagedList<Object>> getPagedList(#Query("page") int page);
}
Hope that helps.
#Alimov Shohrukh, I also tried for many ways for Pagination
1) Check this link,This is one way
2) I mention it step by step
from API side - you need to pass pageConunt, pageIndex and get data based on above parameters
pageConunt - means how many data you want get from server for i.e - 10
pageIndex - page number for i.e 1,2,3 etc
public class DemoActivity extends BaseActivity{
List<BaseModel> orderList = new ArrayList<>();
ListAdapter listAdapter;
LinearLayoutManager layoutManager;
OrderListAdapter orderListAdapter;
int pageIndex = 1; // you can pass 1,2,3...
int pageCount = 10; //you can pass 10,20...
boolean isApiSuccess = false;
//if api get success == true then you need to work with load more sp we take one boolean variable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
findView();
setRecyclerViewPagination();
}
private void findView() {
//recyclerview
rv_po_order_number = findViewById(R.id.rv_po_order_number);
}
//custom OnScrollListener
private RecyclerView.OnScrollListener recyclerViewOnScrollListener = 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) {
super.onScrolled(recyclerView, dx, dy);
if (isApiSuccess) {
pageIndex++;
listTestApiCall(pageIndex, searchQuery);
Log.e(TAG, pageIndex + " page count ");
orderListAdapter.showLoading(true);
rv_po_order_number.post(new Runnable() {
public void run() {
// There is no need to use notifyDataSetChanged()
orderListAdapter.notifyDataSetChanged();
}
});
}
}
};
private void setRecyclerViewPagination() {
orderList = new ArrayList<>();
orderListAdapter = new OrderListAdapter(mActivity, orderList);
layoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
rv_po_order_number.setLayoutManager(layoutManager);
rv_po_order_number.setHasFixedSize(true);
rv_po_order_number.setAdapter(orderListAdapter);
rv_po_order_number.addOnScrollListener(recyclerViewOnScrollListener);
listTestApiCall(pageCount,pageIndex);
}
private void listTestApiCall(final int pageCount,final int pageIndex) {
// if (CommonUtils.isConnectingToInternet(mActivity)) {
if (validateInternetConn(mActivity)) {//check internet
final boolean isFirstPage = pageIndex == 1 ? true : false;
if (isFirstPage)
//do your stuff - if you want to show loader
Call<BaseModel> call = ApiClient.getClient().listApiCall(pageCount, pageIndex);
call.enqueue(new Callback<BaseModel>() {
#Override
public void onResponse(Call<BaseModel> call, Response<BaseModel> response) {
try {
if (response.isSuccessful()) {
boolean success = response.body().getStatus();
isApiSuccess = response.body().getStatus();
if (success) {
List<BaseModel> list = new ArrayList<>();
if (response.body().getData() != null) {
list = response.body().getData();
if (isFirstPage)
orderList.clear();
orderList.addAll(response.body().getData());
}
if (list != null && list.size() > 0) {
isApiSuccess = true;
} else {
isApiSuccess = false;
}
} else if (!success) {
isApiSuccess = false;
String message = response.body().getMessage();
}
listAdapter.showLoading(false);
listAdapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
Log.e("Tag", "error=" + e.toString());
isApiSuccess = false;
}
}
#Override
public void onFailure(Call<BaseModel> call, Throwable t) {
Log.e("Tag", "error" + t.toString());
isApiSuccess = false;
}
});
}
}
}
here is OrderListAdapter
public class OrderListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
Activity mActivity;
List<OrderListBaseModel.DataBean> mList;
PurchaseOrderReceiveOnClick purchaseOrderReceiveOnClick;
DeleteUpdatePOOnClick deleteUpdatePOOnClick;
public static final int TYPE_FOOTER = 1;
public static final int TYPE_ITEM = 2;
protected boolean showLoader = true;
public OrderListAdapter(Activity mActivity, List<OrderListBaseModel.DataBean> mList, PurchaseOrderReceiveOnClick purchaseOrderReceiveOnClick,DeleteUpdatePOOnClick deleteUpdatePOOnClick) {
this.mActivity = mActivity;
this.purchaseOrderReceiveOnClick = purchaseOrderReceiveOnClick;
this.deleteUpdatePOOnClick = deleteUpdatePOOnClick;
this.mList = mList;
}
public OrderListAdapter(Activity mActivity, List<OrderListBaseModel.DataBean> mList) {
this.mActivity = mActivity;
this.mList = mList;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_ITEM) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_purchase_order_receive, parent, false);
return new DataViewHolder(v, purchaseOrderReceiveOnClick);
} else if (viewType == TYPE_FOOTER) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.loading_layout, parent, false);
return new FooterViewHolder(v);
} else
return null;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof DataViewHolder) {
final DataViewHolder dataViewHolder = (DataViewHolder) holder;
final OrderListBaseModel.DataBean dataBean = getItem(position);
if (dataBean != null) {
dataViewHolder.setPosition(position);
dataViewHolder.setSingleBean(dataBean);
}
}
}
private OrderListBaseModel.DataBean getItem(int position) {
if (mList.size() > 0)
return mList.get(position);
else
return null;
}
public void showLoading(boolean status) {
showLoader = status;
}
#Override
public int getItemViewType(int position) {
if ((position == mList.size() - 1) && showLoader) {
return TYPE_FOOTER;
}
return TYPE_ITEM;
}
public void removeItem(int position) {
mList.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
return mList.size();
}
public static class DataViewHolder extends RecyclerView.ViewHolder {
int position;
OrderListBaseModel.DataBean dataBean;
private TextView tv_row_po_no,textViewOptions;
public DataViewHolder(View v, final PurchaseOrderReceiveOnClick purchaseOrderReceiveOnClick) {
super(v);
tv_row_po_no = v.findViewById(R.id.tv_row_po_no);
textViewOptions = v.findViewById(R.id.textViewOptions);
}
public void setPosition(int position) {
this.position = position;
}
public void setSingleBean(OrderListBaseModel.DataBean dataBean) {
this.dataBean = dataBean;
}
}
private class FooterViewHolder extends RecyclerView.ViewHolder {
public FooterViewHolder(View view) {
super(view);
}
}
}
here is xml code
loading_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/linearRoot"
android:gravity="center_horizontal"
android:layout_marginTop="#dimen/_5sdp">
<com.app.trackpoint.custom_loader.MYLoader
android:layout_width="#dimen/_30sdp"
app:my_color="#color/colorAccent"
android:layout_height="#dimen/_30sdp" />
</LinearLayout>
I am using Recyclerview to achieve endless recyclerview scroll listener. Now it loading only page = 1 and page = 2 while scrolling but it not loading another pages, and I added EndlessRecyclerViewScrollListener class from github.
Activity
public class AccountPagination extends AppCompatActivity implements RestCallback {
String UserId, rollname, username, name, fname, lname, emailid, contact_no, gender1, date_of_birth, country_id, postal_code, profession_response, Street_Address, City;
NonScrollListView listItem;
public static AccountStatementAdapter adapter;
ArrayList<AccountStatementModel> AccountStatementList;
AccountsSortingAdapter adapterSort;
AccountsTenRecordsAdapter adapterTenRecords;
ArrayList<AccountStatementModel> AccountDetailsList;
ArrayList<AccountStatementModel> AccountSortingList;
ArrayList<AccountStatementModel> AccountTenRecordsList;
ArrayList<AccountStatementModel> androidVersions;
List<AccountStatementModel> AccountList;
RecyclerView recyclerView;
int userPage = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_pagination);
initViews();
recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
callAccountStatementAPI(userPage);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(linearLayoutManager);
// recyclerView.setAdapter(adapter);
recyclerView.addOnScrollListener(new EndlessRecyclerViewScrollListener(linearLayoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
userPage++;
callAccountStatementAPI(userPage);
}
});
//RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
//RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 1);
}
public void initViews() {
Intent i = getIntent();
UserId = i.getStringExtra("id");
name = SharedPref.read(SharedPref.FIRST_NAME, "") + "\t" + SharedPref.read(SharedPref.LAST_NAME, "");
String Hello = "Hello " + name;
getSupportActionBar().setSubtitle(Hello);
}
private void callAccountStatementAPI(final int page) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("user_id", SharedPref.read(SharedPref.USER_ID, ""));
map.put("page", String.valueOf(page));
RestService.getInstance(AccountPagination.this).getAccount1(map, new MyCallback<ArrayList<AccountStatementModel>>(AccountPagination.this,
AccountPagination.this, true, "Loading ...", GlobalVariables.SERVICE_MODE.ACCOUNT_STATEMENT));
}
#Override
public void onFailure(Call call, Throwable t, GlobalVariables.SERVICE_MODE mode) {
}
#Override
public void onSuccess(Response response, GlobalVariables.SERVICE_MODE mode) {
switch (mode) {
case ACCOUNT_STATEMENT:
androidVersions = (ArrayList<AccountStatementModel>) response.body();
AccountPaginationAdapter adapter = new AccountPaginationAdapter(getApplicationContext(), androidVersions);
androidVersions.addAll((Collection<? extends AccountStatementModel>) response.body());
adapter.notifyItemRangeInserted(adapter.getItemCount(), androidVersions.size()-2);
recyclerView.setAdapter(adapter);
break;
}
}
}
Adapter Class
public class AccountPaginationAdapter extends RecyclerView.Adapter<AccountPaginationAdapter.ViewHolder> {
private ArrayList<AccountStatementModel> android_versions;
private Context context;
private String TAG = "On Click";
String main_url = "http://www.consumer1st.in/ccb/";
public AccountPaginationAdapter(Context context, ArrayList<AccountStatementModel> android_versions) {
this.context = context;
this.android_versions = android_versions;
}
#Override
public AccountPaginationAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.accountpagination_item_list, viewGroup, false);
return new AccountPaginationAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(AccountPaginationAdapter.ViewHolder viewHolder, final int position) {
viewHolder.lable_name.setText(android_versions.get(position).getRemarks());
viewHolder.icon_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String icoon_index_id = android_versions.get(position).getId();
String iconn_id = android_versions.get(position).getUserId();
}
});
}
#Override
public int getItemCount() {
return android_versions.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView lable_name;
ImageView icon_image;
public ViewHolder(View view) {
super(view);
icon_image = (ImageView) itemView.findViewById(R.id.icon_image);
lable_name = (TextView) itemView.findViewById(R.id.lable_name);
}
}
}
Try this you will get perfect result.
int pastVisiblesItems, visibleItemCount, totalItemCount;
recyclerView.addOnScrollListener(new
RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dy > 0) {
visibleItemCount = layoutManager.getChildCount();
totalItemCount = layoutManager.getItemCount();
pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();
if (loading && totalItemCount >= (pastVisiblesItems + 50)) {
userPage++;
callAccountStatementAPI(userPage);
Log.v("...", "Last Item Wow !");
//Do pagination.. i.e. fetch new data
}
}
}
});
Below the code will work But this code totally wrong way actually u are calling every api hit to creating new adapter and adding list. See more pagination examples and change it.. See reference here.
Write a method in Adapter Class:
public void addMoreItems(ArrayList<AccountStatementModel> newItems){
androidVersions.addAll(newItems);
}
Write Activity:
case ACCOUNT_STATEMENT:
androidVersions = (ArrayList<AccountStatementModel>) response.body();
AccountPaginationAdapter adapter = new AccountPaginationAdapter(getApplicationContext(), androidVersions);
androidVersions.addAll((Collection<? extends AccountStatementModel>) response.body());
adapter.addMoreItems(androidVersions);
adapter.notifyItemRangeInserted(adapter.getItemCount(), androidVersions.size()-2);
recyclerView.setAdapter(adapter);
break;
}
Image before scroll - Image After Scroll
I'm trying to develop application like wallpaper app when i select any category then open it and when i scroll this RecyclerView that time load page 2 images from api and so on but when i scroll RecyclerView image change it's position and load duplicate of it. plz help me to solved this.
My Adapter :
public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mCtx;
private ImageView link;
private boolean isLoading;
private List<Image> imageList;
private int visibleThreshold = 4;
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private int lastVisibleItem, totalItemCount;
private OnLoadMoreListener onLoadMoreListener;
public ImageAdapter(RecyclerView recyclerView, List<Image> imageList, Context mCtx) {
this.mCtx = mCtx;
this.imageList = imageList;
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager gridLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = gridLayoutManager.getItemCount();
lastVisibleItem = gridLayoutManager.findLastVisibleItemPosition();
if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
// }
});
}
}
public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.onLoadMoreListener = mOnLoadMoreListener;
}
#Override
public int getItemViewType(int position) {
return imageList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.list_items, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
} else if (viewType == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_loading, parent, false);
LoadingViewHolder vh1 = new LoadingViewHolder(view);
return vh1;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof ViewHolder) {
final Image image = imageList.get(position);
final String imgUrl = image.getThumb();
link.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), ViewImage.class);
intent.putExtra("URL", imgUrl);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(intent);
}
});
Glide.with(mCtx).load(imgUrl).into(link);
} else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return imageList.size();
}
public void setLoaded() {
isLoading = false;
}
private class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
LoadingViewHolder(View view) {
super(view);
progressBar = view.findViewById(R.id.progressBar1);
}
}
class ViewHolder extends RecyclerView.ViewHolder {
ViewHolder(View v) {
super(v);
link = v.findViewById(R.id.link);
}
}
}
My Activity :
public class MainActivity extends AppCompatActivity {
int i = 1;
String query;
List<Image> imageList;
RecyclerView listView;
ImageAdapter adapter;
private static String JSON_URL;
private static final String TAG = "Tj";
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//initializing listview and hero list
listView = findViewById(R.id.listView);
imageList = new ArrayList<>();
Intent intent = getIntent();
query = intent.getStringExtra("category");
JSON_URL = "https://api.unsplash.com/search/photos?query=" + query +
"&client_id=xxxxx&page=" + i;
Log.d(TAG, "Query " + JSON_URL);
loadHeroList();
}
private void loadHeroList() {
//getting the progressbar
progressBar = findViewById(R.id.progressBar);
//making the progressbar visible
progressBar.setVisibility(View.VISIBLE);
//creating a string request to send request to the url
StringRequest jsonArrayRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
//we have the array named hero inside the object
//so here we are getting that json array
JSONArray heroArray = obj.getJSONArray("results");
//now looping through all the elements of the json array
for (int i = 0; i < heroArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject jsonObject = heroArray.getJSONObject(i);
JSONObject jsonObject1 = jsonObject.getJSONObject("urls");
//creating a hero object and giving them the values from json object
Image hero = new Image(jsonObject.getString("id"),
jsonObject.getString("color"),
jsonObject1.getString("full"));
//adding the hero to herolist
imageList.add(hero);
listView.setHasFixedSize(true);
// use a grid layout manager
listView.setLayoutManager(new GridLayoutManager(MainActivity.this, 2));
}
//creating custom adapter object
adapter = new ImageAdapter(listView, imageList, getApplicationContext());
//adding the adapter to listview
listView.setAdapter(adapter);
//Load More Pages Start Here
adapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
loadMoreData();
}
});
//Complete for Load More Pages
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(jsonArrayRequest);
}
private void loadMoreData() {
imageList.add(null);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
adapter.notifyItemInserted(imageList.size() - 1);
imageList.remove(imageList.size() - 1);
adapter.notifyItemRemoved(imageList.size());
i++;
Log.d(TAG, "ILoadMore " + i);
String JSON_URL_LoadMore = "https://api.unsplash.com/search/photos?query=" + query + "&client_id=xxxxx&page=" + i;
Log.d(TAG, "QueryLoadMore " + JSON_URL_LoadMore);
StringRequest jsonArrayRequestLoadMore = new StringRequest(Request.Method.GET, JSON_URL_LoadMore,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
//we have the array named hero inside the object
//so here we are getting that json array
JSONArray heroArray = obj.getJSONArray("results");
//now looping through all the elements of the json array
for (int i = 0; i < heroArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject jsonObject = heroArray.getJSONObject(i);
JSONObject jsonObject1 = jsonObject.getJSONObject("urls");
//creating a hero object and giving them the values from json object
Image hero = new Image(jsonObject.getString("id"),
jsonObject.getString("color"),
jsonObject1.getString("full"));
//adding the hero to herolist
imageList.add(hero);
adapter.notifyItemInserted(imageList.size());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
//adding the string request to request queue
requestQueue.add(jsonArrayRequestLoadMore);
adapter.notifyDataSetChanged();
adapter.setLoaded();
}
}, 5000);
}
}
Override
#Override
public long getItemId(int position) {
return position;
}
And use
Picasso.with(context)
.load(getImgUrl)
.placeholder(R.drawable.user_placeholder)
.fit()
.into(imageView);
Or else
To retain and restore recyclerview position on scrolling, please try below link.
https://panavtec.me/retain-restore-recycler-view-scroll-position
How Do I show progress bar at bottom when user reached to items those are visible in a list.
I have written a code in which i am getting data using web service, now i would like to populate partial records, because i have around 630 records in my JSON.
Here is my whole code which i am using to get data from JSON and to populate into RecyclerView.
Here is how my JSON looks, but real JSON contains over 600 records:
http://walldroidhd.com/api.php
Can someone guide me where i have to make changes in my code ?
I want to populate more records whenever user do scroll to bottom using progressbar, still i am showing all the records.
RecyclerViewFragment.java:
public class RecyclerViewFragment extends Fragment {
RecyclerView mRecyclerView;
LinearLayoutManager mLayoutManager;
RecyclerView.Adapter mAdapter;
ArrayList<NatureItem> actorsList;
private int previousTotal = 0;
private boolean loading = true;
private int visibleThreshold = 5;
int firstVisibleItem, visibleItemCount, totalItemCount;
public static RecyclerViewFragment newInstance() {
return new RecyclerViewFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_recyclerview_advance, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
actorsList = new ArrayList<NatureItem>();
new JSONAsyncTask().execute("my JSON url");
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new GridLayoutManager(getActivity(), 2);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = mRecyclerView.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)) {
// End has been reached
Log.i("...", "end called");
// Do something
loading = true;
}
}
});
// mAdapter = new CardAdapter();
mAdapter = new RecyclerViewMaterialAdapter(new CardAdapter(getActivity(), actorsList), 2);
mRecyclerView.setAdapter(mAdapter);
MaterialViewPagerHelper.registerRecyclerView(getActivity(), mRecyclerView, null);
mRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(getActivity(), String.valueOf(position), Toast.LENGTH_LONG).show();
}
})
);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = null;
try {
data = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
}
JSONObject jsono = null;
try {
jsono = new JSONObject(data);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray jarray = jsono.getJSONArray("wallpapers");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
NatureItem actor = new NatureItem();
actor.setName(object.getString("id"));
actor.setThumbnail(object.getString("thumb_url"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
mAdapter.notifyDataSetChanged();
if (result == false) {
Toast.makeText(getActivity(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
else {
}
}
}
}
CardAdapter.java:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private ArrayList<NatureItem> mItems;
private Context mContext;
public CardAdapter(Context context, ArrayList<NatureItem> feedItemList) {
this.mItems = feedItemList;
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.recycler_view_card_item, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
NatureItem nature = mItems.get(i);
viewHolder.tvNature.setText(nature.getName());
Picasso.with(mContext).load(nature.getThumbnail())
.error(R.mipmap.ic_launcher)
.placeholder(R.mipmap.ic_launcher)
.into(viewHolder.imgThumbnail);
}
#Override
public int getItemCount() {
return mItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public ImageView imgThumbnail;
public TextView tvNature;
public ViewHolder(View itemView) {
super(itemView);
imgThumbnail = (ImageView)itemView.findViewById(R.id.img_thumbnail);
tvNature = (TextView)itemView.findViewById(R.id.tv_nature);
}
}
}
Here is how i have implemented Endless as well, using this:
mRecyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener(linearLayoutManager) {
#Override
public void onLoadMore(int current_page) {
// do something...
}
});
Note: I would personally prefer RecyclerView onScroll functionality to get my work done.
Activity Class with recylcerview in xml layout file
public class WallpaperActivity extends AppCompatActivity implements OnTaskCompleted {
private static final String TAG = "WallpaperActivity";
private Toolbar toolbar;
private RecyclerView mRecyclerView;
private WallPaperDataAdapter mAdapter;
private LinearLayoutManager mLayoutManager;
// to keep track which pages loaded and next pages to load
public static int pageNumber;
private List<WallPaper> wallpaperImagesList;
protected Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wallpaper_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
pageNumber = 1;
wallpaperImagesList = new ArrayList<WallPaper>();
handler = new Handler();
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("WallPapers");
}
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
// use a linear layout manager
mRecyclerView.setLayoutManager(mLayoutManager);
// create an Object for Adapter
mAdapter = new WallPaperDataAdapter(wallpaperImagesList, mRecyclerView);
// set the adapter object to the Recyclerview
mRecyclerView.setAdapter(mAdapter);
getWebServiceData();
mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
//add null , so the adapter will check view_type and show progress bar at bottom
wallpaperImagesList.add(null);
mAdapter.notifyItemInserted(wallpaperImagesList.size() - 1);
++pageNumber;
getWebServiceData();
}
});
}
public void getWebServiceData() {
BackGroundTask backGroundTask = new BackGroundTask(this, this, pageNumber);
backGroundTask.execute();
}
#Override
public void onTaskCompleted(String response) {
parsejosnData(response);
}
public void parsejosnData(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
// String json = jsonObject.toString();
JSONArray jsonArray = jsonObject.getJSONArray("wallpapers");
if (jsonArray != null) {
// looping through All albums
if (pageNumber > 1) {
wallpaperImagesList.remove(wallpaperImagesList.size() - 1);
mAdapter.notifyItemRemoved(wallpaperImagesList.size());
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item values in variable
String id = c.getString("id");
String orig_url = c.getString("orig_url");
String thumb_url = c.getString("thumb_url");
String downloads = c.getString("downloads");
String fav = c.getString("fav");
// Creating object for each product
WallPaper singleWall = new WallPaper(id, orig_url, thumb_url, downloads, fav);
// adding HashList to ArrayList
wallpaperImagesList.add(singleWall);
handler.post(new Runnable() {
#Override
public void run() {
mAdapter.notifyItemInserted(wallpaperImagesList.size());
}
});
}
mAdapter.setLoaded();
} else {
Log.d("Wallpapers: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Adapter Class
public class WallPaperDataAdapter extends RecyclerView.Adapter {
private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0;
private List<WallPaper> imagesList;
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
public WallPaperDataAdapter(List<WallPaper> imagesList1, RecyclerView recyclerView) {
imagesList = imagesList1;
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView
.getLayoutManager();
recyclerView
.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView,
int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager
.findLastVisibleItemPosition();
if (!loading
&& totalItemCount <= (lastVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public int getItemViewType(int position) {
return imagesList.get(position) != null ? VIEW_ITEM : VIEW_PROG;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
RecyclerView.ViewHolder vh;
if (viewType == VIEW_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.wallpaper_row, parent, false);
vh = new WallPaperViewHolder(v);
} else {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.progress_item, parent, false);
vh = new ProgressViewHolder(v);
}
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof WallPaperViewHolder) {
WallPaper singleWallPaper = (WallPaper) imagesList.get(position);
Glide.with(((WallPaperViewHolder) holder).thumbIcon.getContext())
.load(singleWallPaper.getThumbUrl())
.centerCrop()
.placeholder(R.drawable.bg)
.crossFade()
.into(((WallPaperViewHolder) holder).thumbIcon);
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
}
}
public void setLoaded() {
loading = false;
}
#Override
public int getItemCount() {
return imagesList.size();
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
//
public static class WallPaperViewHolder extends RecyclerView.ViewHolder {
public ImageView thumbIcon;
public WallPaperViewHolder(View v) {
super(v);
thumbIcon = (ImageView) v.findViewById(R.id.thumbIcon);
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar1);
}
}
}
wallpaper_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/thumbIcon"
android:layout_width="160dp"
android:layout_height="160dp"
android:layout_centerInParent="true"
android:layout_margin="2dp"
android:gravity="center" />
</RelativeLayout>
progress_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_height="wrap_content" />
</LinearLayout>
Separate BackGroundTask.java
public class BackGroundTask extends AsyncTask<Object, Void, String> {
private ProgressDialog pDialog;
public OnTaskCompleted listener = null;//Call back interface
Context context;
int pageNumber;
public BackGroundTask(Context context1, OnTaskCompleted listener1, int pageNumber) {
context = context1;
listener = listener1; //Assigning call back interface through constructor
this.pageNumber = pageNumber;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Object... params) {
//My Background tasks are written here
synchronized (this) {
String url = Const.URL_WALLPAPERS_HD + pageNumber;
String jsonStr = ServiceHandler.makeServiceCall(url, ServiceHandler.GET);
Log.i("Url: ", "> " + url);
Log.i("Response: ", "> " + jsonStr);
return jsonStr;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
listener.onTaskCompleted(result);
}
}
ServiceHanlder.java
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
*
* #url - url to make request
* #method - http request method
*/
public static String makeServiceCall(String url, int method) {
return makeServiceCall(url, method, null);
}
/**
* Making service call
*
* #url - url to make request
* #method - http request method
* #params - http request params
*/
public static String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
Log.e("Selltis Request URL", url);
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += paramString;
Log.i("Request URL", url);
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "Fail";
} catch (ClientProtocolException e) {
e.printStackTrace();
return "Fail";
} catch (IOException e) {
e.printStackTrace();
return "Fail";
}
return response;
}
}
Interface for Load More
public interface OnLoadMoreListener {
void onLoadMore();
}
Interface to know web service data loaded from asynctask
public interface OnTaskCompleted{
void onTaskCompleted(String response);
}
Please let me know if this works or any issues for you.
Better to use Volley or okHttp Libraries for Networking.
For ImageLoading i used Glide Library.
This is how I detect whether RecyclerView should refresh by OnScrollListener, take a look at it:
recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
int ydy = 0;
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int offset = dy - ydy;
ydy = dy;
boolean shouldRefresh = (linearLayoutManager.findFirstCompletelyVisibleItemPosition() == 0)
&& (recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING) && offset > 30;
if (shouldRefresh) {
//swipeRefreshLayout.setRefreshing(true);
//Refresh to load data here.
return;
}
boolean shouldPullUpRefresh = linearLayoutManager.findLastCompletelyVisibleItemPosition() == linearLayoutManager.getChildCount() - 1
&& recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING && offset < -30;
if (shouldPullUpRefresh) {
//swipeRefreshLayout.setRefreshing(true);
//refresh to load data here.
return;
}
swipeRefreshLayout.setRefreshing(false);
}
});
Hope you'll be inspired. Good luck~
To implement OnScrollListener in Kotlin for RecyclerView, you can use
recyclerViewChat.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
Log.d("scroll", "idle")
} else if (newState == RecyclerView.SCROLL_STATE_SETTLING) {
Log.d("scroll", "settling")
} else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
Log.d("scroll", "dragging")
}
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
Log.d("scroll", "scrolling")
}
})
Another example. Set you progress bar at bottom and change its visibility according to scrolling/loading and your records. Note: you need to call notifyDataSetChanged(); method to add/refresh data to adapter
recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int total = linearLayoutManager.getItemCount();
int firstVisibleItemCount = linearLayoutManager.findFirstVisibleItemPosition();
int lastVisibleItemCount = linearLayoutManager.findLastVisibleItemPosition();
//to avoid multiple calls to loadMore() method
//maintain a boolean value (isLoading). if loadMore() task started set to true and completes set to false
if (!isLoading) {
if (total > 0)
if ((total - 1) == lastVisibleItemCount){
loadMore();//your HTTP stuff goes in this method
loadingProgress.setVisibility(View.VISIBLE);
}else
loadingProgress.setVisibility(View.GONE);
}
}
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
});
The idea to implement load-more is :
Get all records in one collection. Take another collection which will populate partial records lets say 10 records. Now, when u reach at bottom, populate next 10 records in the collection and notify the list.
So your code will be something like this :
ArrayList<NatureItem> tempList; // which holds partial records
tempList = getList(limit, 10);
mAdapter = new RecyclerViewMaterialAdapter(new CardAdapter(getActivity(), tempList), 2);
mRecyclerView.setAdapter(mAdapter);
Now, code to load next records :
limit += 10;
tempList.addAll(getList(limit, 10));
mAdapter.notifyDataSetChanged();
To show he loader/progress, better to use load-more library
In the onScroll method
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)) {
// End has been reached
Log.i("...", "end called");
// Do something
new JSONAsyncTask().execute("http://walldroidhd.com/api.php");
loading = true;
}
Now accepted answer as #SilentKnight suggested will not work as setOnscroll is deprecated by Android SDK.
You should use
recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
int ydy = 0;
#Override
public void onScrollStateChanged(#NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int offset = dy - ydy;
ydy = dy;
boolean shouldRefresh = (linearLayoutManager.findFirstCompletelyVisibleItemPosition() == 0)
&& (recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING) && offset > 30;
if (shouldRefresh) {
//swipeRefreshLayout.setRefreshing(true);
//Refresh to load data here.
return;
}
boolean shouldPullUpRefresh = linearLayoutManager.findLastCompletelyVisibleItemPosition() == linearLayoutManager.getChildCount() - 1
&& recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING && offset < -30;
if (shouldPullUpRefresh) {
//swipeRefreshLayout.setRefreshing(true);
//refresh to load data here.
return;
}
swipeRefreshLayout.setRefreshing(false);
}
});
I want to load more contents from my adapter while scrolling the recycler view.I implemented it, but its not working. my recycler view works perfectly, but I am not able to load rest of the contents from my list while scrolling. Presently there is no error in my code. but I couldn't load more items while scrolling. please help.
This is my main activity.
public class Contact_school extends AppCompatActivity implements SearchView.OnQueryTextListener {
private List<Contact> Listcontact = new ArrayList<>();
Contacts_Adapter cadapter;
private RecyclerView rv;
public String GET_CONTACTS = "http://xyzx.com/Publicpages_mob/brief_school_details";
public Contact contact;
public String school_id;
String tag_json_obj = "json_obj_req";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_school);
rv = (RecyclerView) findViewById(R.id.recycler_view);
preparelist();
cadapter = new Contacts_Adapter(Listcontact, rv);
final LinearLayoutManager layoutManager = new LinearLayoutManager(Contact_school.this);
rv.setLayoutManager(layoutManager);
rv.setItemAnimator(new DefaultItemAnimator());
rv.setAdapter(cadapter);
rv.setHasFixedSize(true);
cadapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
Log.v(" KILILII ", "KITTTI");
//add null , so the adapter will check view_type and show progress bar at bottom
//// Listcontact.add(null);
//// cadapter.notifyItemInserted(Listcontact.size() - 1);
// remove progress item
//// Listcontact.remove(Listcontact.size() - 1);
//// cadapter.notifyItemRemoved(Listcontact.size());
// //add items one by one
int start = Listcontact.size();
int end = start + 20;
for (int i = start + 1; i <= end; i++) {
Listcontact.add(contact);
cadapter.notifyItemInserted(Listcontact.size());
}
cadapter.setLoaded();
//or you can add all at once but do not forget to call mAdapter.notifyDataSetChanged();
}
});
}
private void preparelist() {
final StringRequest strReq = new StringRequest(Request.Method.POST, GET_CONTACTS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
Log.e("RESPONSE TEST", "" + jObj);
JSONArray jsonArray = jObj.getJSONArray("school_details");
Log.e("RESPONSE ARRAY", "" + jsonArray);
Log.d("SUCESS ", response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
contact = new Contact();
contact.setAddress(jsonobject.getString("school_address"));
contact.setRating(jsonobject.getString("school_rating"));
Listcontact.add(contact);
}
cadapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
}
this is my adapter class
public class Contacts_Adapter extends RecyclerView.Adapter<Contacts_Adapter.MyViewHolder> {
private List<Contact> List1;
private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0;
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView text_address,text_rating;
public MyViewHolder(View view) {
super(view);
text_address = (TextView)view.findViewById(R.id.textaddress);
text_rating = (TextView)view.findViewById(R.id.textrating);
}
}
public Contacts_Adapter(List<Contact> List1,RecyclerView recyclerView)
{
this.List1 = List1;
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView
.getLayoutManager();
recyclerView
.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView,
int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager
.findLastVisibleItemPosition();
if (!loading
&& totalItemCount <= (lastVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public int getItemViewType(int position) {
return List1.get(position) != null ? VIEW_ITEM : VIEW_PROG;
}
#Override
public Contacts_Adapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
Contact c = List1.get(position);
holder.text_rating.setText("Rating "+c.getRating());
holder.text_address.setText(c.getAddress());
}
public void setLoaded() {
loading = false;
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
this is my model class
public class Contact implements Serializable {
private static final long serialVersionUID = 1L;
private String address,rating;
public Contact(){
}
public Contact (String address, String rating){
this.address = address;
this.rating= rating;
}
public String getAddress(){ return address;}
public String getRating( ){return rating;}
public void setAddress(String ad){ this.address= ad;}
public void setRating(String ad){ this.rating= ad;}
}
and I have this interface
public interface OnLoadMoreListener {
void onLoadMore();
}
please help
You don't need to track the scroll to know when to search more itens.
You can call the Volley request from the onBindViewHolder, for example:
int itemsBeforeUpdate = 10;
public void onBindViewHolder(MyViewHolder holder, final int position) {
Contact c = List1.get(position);
holder.text_rating.setText("Rating "+c.getRating());
holder.text_address.setText(c.getAddress());
if(List1.size() - position <10){
// Do your Volley Request, add response to the list and notify the adapter that the data changed
}
}
Instead of calling OnLoadMoreListener in the following block
if (!loading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
Just perform your load more request in this block only. Like:
if (!loading&& totalItemCount <= (lastVisibleItem + visibleThreshold)) {
// Load your volley request or load more request her
loading = true;
}
and after that notify the adapter that data has been changed.
Instead of adding the values to the list in the activity class, try it by adding it to the adapter class. Say for example add an method in adapter like below.
public void addContact(Contact contact) {
list.add(contact);
notifyItemInserted(list.size());
}
And in the activity instead of this,
YOUR CODE:
cadapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
Log.v(" KILILII ", "KITTTI");
//add null , so the adapter will check view_type and show progress bar at bottom
//// Listcontact.add(null);
//// cadapter.notifyItemInserted(Listcontact.size() - 1);
// remove progress item
//// Listcontact.remove(Listcontact.size() - 1);
//// cadapter.notifyItemRemoved(Listcontact.size());
// //add items one by one
int start = Listcontact.size();
int end = start + 20;
for (int i = start + 1; i <= end; i++) {
Listcontact.add(contact);
cadapter.notifyItemInserted(Listcontact.size());
}
cadapter.setLoaded();
//or you can add all at once but do not forget to call mAdapter.notifyDataSetChanged();
}
});
TRY THIS:
cadapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
Log.v(" KILILII ", "KITTTI");
int start = Listcontact.size();
int end = start + 20;
for (int i = start + 1; i <= end; i++) {
cadapter.addContact(contact);
}
cadapter.setLoaded();
}
});
Hope this helpful :)