From JSON file I get almost (200-300 image URL), I'm trying to load 10 images by 10 images to make the images load quickly instead of loading all the images (200-300) at once .but I have a problem RecyclerView Stop scrolling after the first 10 items, here's what I have tried:
InfiniteScrollListener.java
private void initInfiniteScrollListener(LinearLayoutManager mLayoutManager) {
infiniteScrollListener = new InfiniteScrollListener(mLayoutManager) {
#Override
public void onLoadMore(int page) {
pb.setVisibility(View.VISIBLE);
refreshContent();
}
};
recyclerView.addOnScrollListener(infiniteScrollListener);
}
Method to set adapter:
private void refreshContent() {
fetchRemoteData(new DataStatus() {
#Override
public void onSuccess(List<Post> posts) {
loading.setVisibility(View.GONE);
pb.setVisibility(View.GONE);
if (adapter == null) {
adapter = new MyAdapter(posts, getActivity(), new RecyclerViewClickListener() {
#Override
public void onClick(View view, Post post) {
}
});
recyclerView.setAdapter(adapter);
} else {
int position = adapter.getItemCount();
adapter.getItems().addAll(posts);
adapter.notifyItemRangeInserted(position, position + 10);
}
}
#Override
public void onError(Exception e) {
slowinternetconnection();
}
});
}
Fetching data:
private void fetchRemoteData(final DataStatus callback) {
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
List<Post> listItems = new ArrayList<>();
List<Post> PagintationList = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("bgs");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
Post item = new Post(
o.optString("img"),
o.optString("name")
);
listItems.add(item);
}
for (int count = resetNumber; count < 10; count++) {
PagintationList.add(listItems.get(count));
}
resetNumber = PagintationList.size() + 1;
callback.onSuccess(PagintationList);
} catch (JSONException e) {
slowinternetconnection();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callback.onError(error);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
stringRequest.setShouldCache(false);
requestQueue.getCache().clear();
requestQueue.add(stringRequest);
}
What I want is:
From 250 images for example, I want to load 10 images each time user scroll recyclerview, until 250 image to have been completed
private void populateData() {
int i = 0;
while (i < 10) {
rowsArrayList.add("Item " + i);
i++;
}
}
private void initAdapter() {
recyclerViewAdapter = new RecyclerViewAdapter(rowsArrayList);
recyclerView.setAdapter(recyclerViewAdapter);
}
private void initScrollListener() {
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#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);
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (!isLoading) {
if (linearLayoutManager != null && linearLayoutManager.findLastCompletelyVisibleItemPosition() == rowsArrayList.size() - 1) {
//bottom of list!
loadMore();
isLoading = true;
}
}
}
});
}
private void loadMore() {
rowsArrayList.add(null);
recyclerViewAdapter.notifyItemInserted(rowsArrayList.size() - 1);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
rowsArrayList.remove(rowsArrayList.size() - 1);
int scrollPosition = rowsArrayList.size();
recyclerViewAdapter.notifyItemRemoved(scrollPosition);
int currentSize = scrollPosition;
int nextLimit = currentSize + 10;
while (currentSize - 1 < nextLimit) {
rowsArrayList.add("Item " + currentSize);
currentSize++;
}
recyclerViewAdapter.notifyDataSetChanged();
isLoading = false;
}
}, 2000);
}
In Adapter Class
public class RecyclerViewAdapter extends RecyclerView.Adapter {
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
public List<String> mItemList;
public RecyclerViewAdapter(List<String> itemList) {
mItemList = itemList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);
return new ItemViewHolder(view);
} else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_loading, parent, false);
return new LoadingViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int position) {
if (viewHolder instanceof ItemViewHolder) {
populateItemRows((ItemViewHolder) viewHolder, position);
} else if (viewHolder instanceof LoadingViewHolder) {
showLoadingView((LoadingViewHolder) viewHolder, position);
}
}
#Override
public int getItemCount() {
return mItemList == null ? 0 : mItemList.size();
}
/**
* The following method decides the type of ViewHolder to display in the RecyclerView
*
* #param position
* #return
*/
#Override
public int getItemViewType(int position) {
return mItemList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
private class ItemViewHolder extends RecyclerView.ViewHolder {
TextView tvItem;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
tvItem = itemView.findViewById(R.id.tvItem);
}
}
private class LoadingViewHolder extends RecyclerView.ViewHolder {
ProgressBar progressBar;
public LoadingViewHolder(#NonNull View itemView) {
super(itemView);
progressBar = itemView.findViewById(R.id.progressBar);
}
}
private void showLoadingView(LoadingViewHolder viewHolder, int position) {
//ProgressBar would be displayed
}
private void populateItemRows(ItemViewHolder viewHolder, int position) {
String item = mItemList.get(position);
viewHolder.tvItem.setText(item);
}
Check out this link
https://www.journaldev.com/24041/android-recyclerview-load-more-endless-scrolling
you can load 10 items first then refreshing and load next 10.
Related
I've got a RecylerView that is displaying a list of data. I need to add dividers or spacers that I need to add two Dividers or spacers too that I can add text to as shown in the image below(with the text DEFAULT or OTHER).
*NOTE Headers are in the image below with the text "DEFAULT" and another that says "OTHER".
The CC's shown are drag and drop items but i don't want the "spaces or headers" marked as default and other to be moved.
I've started adding the divider as shown in the code below but I cannot figure out how to add text.
#Override
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
LinearLayoutManager mAdapterLayoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(mAdapterLayoutManager);
billingMethodRecyclerViewAdapter = new BillingMethodRecyclerViewAdapter(context, billingMethods, paymentService, ListPaymentMethods.this );
billingMethodRecyclerViewAdapter.setMasterpassService(masterpassService);
billingMethodRecyclerViewAdapter.setChoosePaymentMode(choosePaymentMode);
DividerItemDecoration itemDecor = new DividerItemDecoration(context, mAdapterLayoutManager.getOrientation());
recyclerView.addItemDecoration(itemDecor);
recyclerView.setAdapter(billingMethodRecyclerViewAdapter);
billingMethodRecyclerViewAdapter.clear();
if (!choosePaymentMode) {
setupSwipeListener(billingMethodRecyclerViewAdapter);
}
if (!BuildConfig.SHOW_AVAILABILITY_INRIX) {
parkmobileProAd.setVisibility(View.GONE);
}
if (getArguments() != null) {
isAddPaymentZoneDetails = getArguments().getBoolean(AddPaymentActivity.ADD_PAYMENT_FROM_ZONE_DETAIL);
}
}
and the xml for the recylcerview
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
EDIT
Adapter:
public class BillingMethodRecyclerViewAdapter extends RecyclerView.Adapter<BillingMethodHolder> {
private static final int PENDING_REMOVAL_TIMEOUT = 3000; // in milliseconds
private ArrayList<BillingMethod> billingMethods;
private Handler handler = new Handler(); // handler for running delayed runnables
private HashMap<BillingMethod, Runnable> pendingRunnables = new HashMap<>(); // map of items to pending runnables, so we can cancel a removal if need be
private BillingMethodHolder.BillingMethodListener billingMethodListener;
private PaymentService paymentService;
private MasterpassService masterpassService;
private boolean choosePaymentMode = false;
private Context mContext;
private int maxPaymentMethods = 6;
public BillingMethodRecyclerViewAdapter(Context context, ArrayList<BillingMethod> objects, PaymentService paymentService, BillingMethodHolder.BillingMethodListener billingMethodListener) {
this.billingMethods = objects;
this.billingMethodListener = billingMethodListener;
this.mContext = context.getApplicationContext();
this.paymentService = paymentService;
}
public int getMaxPaymentMethods() {
return maxPaymentMethods;
}
public void setMaxPaymentMethods(int maxPaymentMethods) {
this.maxPaymentMethods = maxPaymentMethods;
}
public void setMasterpassService(MasterpassService masterpassService) {
this.masterpassService = masterpassService;
}
public boolean onItemMove(int fromPosition, int toPosition) {
if (fromPosition < toPosition) {
for (int i = fromPosition; i < toPosition; i++) {
Collections.swap(billingMethods, i, i + 1);
}
} else {
for (int i = fromPosition; i > toPosition; i--) {
Collections.swap(billingMethods, i, i - 1);
}
}
notifyItemMoved(fromPosition, toPosition);
return true;
}
public List<BillingMethod> getBillingMethods() {
return billingMethods;
}
public void setChoosePaymentMode(boolean choosePaymentMode) {
this.choosePaymentMode = choosePaymentMode;
}
#NonNull
#Override
public BillingMethodHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_payment_methods, parent, false);
return new BillingMethodHolder(v);
}
#Override
public void onBindViewHolder(#NonNull BillingMethodHolder holder, final int position) {
holder.bind(getBillingMethods().get(position), billingMethodListener, choosePaymentMode);
}
#Override
public int getItemCount() {
return billingMethods.size();
}
public void pendingRemoval(int position) {
final BillingMethod billingMethod = billingMethods.get(position);
billingMethod.setPendingDeletion(true);
this.notifyItemChanged(position); // redraw row in "undo" state
Runnable pendingRemovalRunnable = () -> {
deleteBillingMethod(position);
};
handler.postDelayed(pendingRemovalRunnable, PENDING_REMOVAL_TIMEOUT);
pendingRunnables.put(billingMethod, pendingRemovalRunnable);
}
public void savePaymentOrder() {
List<BillingMethod> newOrder = new ArrayList<>();
int order = 0;
for (BillingMethod method : billingMethods) {
if (order == 0) {
method.setPreferred(true);
LocalyticsUtil.getInstance(mContext).setPrimaryPaymentMethod(method);
} else {
method.setPreferred(false);
}
method.setSortOrder(order);
newOrder.add(method);
order++;
}
paymentService.setPaymentMethodsOrder(newOrder, new PaymentService.GenericListener() {
#Override
public void onSuccess() {
Log.d("TAG", "Saved");
}
#Override
public void onError(String errorMessage) {
Log.d("TAG", "Saved");
}
});
}
private void deleteBillingMethod(int position) {
BillingMethod method = billingMethods.get(position);
if (method.getBillingType() == BillingType.CREDIT_CARD) {
paymentService.deleteCreditCard(method.getCreditCard().getCardStatus(), new PaymentService.GenericListener() {
#Override
public void onSuccess() {
billingMethods.remove(position);
notifyItemRemoved(position);
}
#Override
public void onError(String errorMessage) {
}
});
} else if (method.getBillingType() == BillingType.PREPAID) {
paymentService.deleteWallet(new PaymentService.GenericListener() {
#Override
public void onSuccess() {
billingMethods.remove(position);
notifyItemRemoved(position);
}
#Override
public void onError(String errorMessage) {
}
});
} else if (method.getBillingType() == BillingType.PAYPAL) {
paymentService.deletePaypal(new PaymentService.GenericListener() {
#Override
public void onSuccess() {
billingMethods.remove(position);
notifyItemRemoved(position);
}
#Override
public void onError(String errorMessage) {
}
});
} else if (method.getBillingType() == BillingType.CHASEPAY) {
paymentService.deleteChasepay(new PaymentService.GenericListener() {
#Override
public void onSuccess() {
billingMethods.remove(position);
notifyItemRemoved(position);
}
#Override
public void onError(String errorMessage) {
}
});
} else if (method.getBillingType() == BillingType.MASTERPASSV7) {
masterpassService.deleteMasterpassV7(String.valueOf(method.getBillingMethodId()), new MasterpassService.GenericListener() {
#Override
public void onSuccess() {
billingMethods.remove(position);
notifyItemRemoved(position);
}
#Override
public void onError(String errorMessage) {
}
});
} else {
notifyDataSetChanged();
}
}
public void clear() {
billingMethods.clear();
notifyDataSetChanged();
}
public void stopRemoval(BillingMethod billingMethod) {
Runnable pendingRemovalRunnable = pendingRunnables.get(billingMethod);
pendingRunnables.remove(billingMethod);
if (pendingRemovalRunnable != null) {
handler.removeCallbacks(pendingRemovalRunnable);
}
billingMethod.setPendingDeletion(false);
this.notifyItemChanged(billingMethods.indexOf(billingMethod));
}
}
I took a bit of time but I was able to do it.
This is the output
1) MainActivity.java
public class MainActivity extends AppCompatActivity implements OnStartDragListener{
RecyclerView recyclerView;
private ItemTouchHelper mItemTouchHelper;
private List<Item> itemList = new ArrayList<>();
private RecyclerViewAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mAdapter = new RecyclerViewAdapter(itemList, MainActivity.this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new SeparationDecorator());
recyclerView.setAdapter(mAdapter);
ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(mAdapter);
mItemTouchHelper = new ItemTouchHelper(callback);
mItemTouchHelper.attachToRecyclerView(recyclerView);
prepareItemData();
}
private void prepareItemData() {
Item item = new Item("Apple Pay");
itemList.add(item);
item = new Item("1706-XXXX-XXXX-1112");
itemList.add(item);
item = new Item("Google pay");
itemList.add(item);
mAdapter.notifyDataSetChanged();
}
#Override
public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
mItemTouchHelper.startDrag(viewHolder);
}
}
2) OnStartDragListener.java
public interface OnStartDragListener {
void onStartDrag(RecyclerView.ViewHolder viewHolder);
}
3) SimpleItemTouchHelperCallback.java
public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {
private final ItemTouchHelperAdapter mAdapter;
public SimpleItemTouchHelperCallback(ItemTouchHelperAdapter adapter) {
mAdapter = adapter;
}
#Override
public boolean isLongPressDragEnabled() {
return true;
}
#Override
public boolean isItemViewSwipeEnabled() {
return false; // make this true to enable swipe to delete
}
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
return makeMovementFlags(dragFlags, swipeFlags);
}
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
RecyclerView.ViewHolder target) {
mAdapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
mAdapter.onItemDismiss(viewHolder.getAdapterPosition());
}
}
4) ItemTouchHelperAdapter.java
public interface ItemTouchHelperAdapter {
void onItemMove(int fromPosition, int toPosition);
void onItemDismiss(int position);
}
5) SeparationDecorator.java
public class SeparationDecorator extends RecyclerView.ItemDecoration {
private int textSize = 50;
private int groupSpacing = 100;
private Paint paint = new Paint();
{
paint.setTextSize(textSize);
}
#Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
for (int i = 0; i < parent.getChildCount(); i++) {
View view = parent.getChildAt(i);
int position = parent.getChildAdapterPosition(view);
if (position == 0) {
c.drawText("DEFAULT", view.getLeft(),
view.getTop() - groupSpacing / 2 + textSize / 3, paint);
} else if(position == 1) {
c.drawText("OTHER", view.getLeft(),
view.getTop() - groupSpacing / 2 + textSize / 3, paint);
}
}
}
#Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (parent.getChildAdapterPosition(view) == 0 || parent.getChildAdapterPosition(view) == 1) {
outRect.set(0, groupSpacing, 0, 0);
}
}
}
6) RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> implements ItemTouchHelperAdapter{
private List<Item> itemList;
private Context context;
#Override
public void onItemMove(int fromPosition, int toPosition) {
Item prev = itemList.remove(fromPosition);
itemList.add(toPosition > fromPosition ? toPosition - 1 : toPosition, prev);
notifyItemMoved(fromPosition, toPosition);
}
#Override
public void onItemDismiss(int position) {
itemList.remove(position);
notifyItemRemoved(position);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
}
}
public RecyclerViewAdapter(List<Item> itemList, Context context) {
this.itemList = itemList;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.view_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Item movie = itemList.get(position);
holder.title.setText(movie.getTitle());
}
#Override
public int getItemCount() {
return itemList.size();
}
}
7) Item.java
public class Item {
private String title;
public Item(String title) {
this.title = title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
This is it. This was able to solve your problem.
I am not able to explain you the complete code, I will take some time in future definitely and explain it.
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
// other methods..
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
// initialize your other views
if (your condition){
// display header
}else{
// hide header
}
}
}
You can do some thing like this by adding header view to the item and displaying for the required set and making it gone for un necessary items.
Simply coming towards what you need, just add an empty view with layout_height="1dp" and background="#bcbcbc" like:
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#bcbcbc"/>
it'll get a line drawn for you, use it as a divider, while for making format difference just use a change text size for texts.
Hope it'll help you.
I have to display 100 data on recycler-view. so I want to implement load more to make it efficient. when I tried to compile the code, the progress bar doesn't go and it leaves big space on the bottom. and it just loaded 20 data not all of them.
this is the code for my adapter
class LoadingViewHolder extends RecyclerView.ViewHolder{
public ProgressBar progressBar;
public LoadingViewHolder(#NonNull View itemView) {
super(itemView);
progressBar=(ProgressBar) itemView.findViewById(R.id.loadmore);
}
}
class herbalViewHolder extends RecyclerView.ViewHolder{
TextView namaHerbal,khasiatHerbal;
ImageView thumbnail;
public herbalViewHolder(#NonNull View itemView) {
super(itemView);
namaHerbal = itemView.findViewById(R.id.nama_herbal);
khasiatHerbal = itemView.findViewById(R.id.khasiat_herbal);
thumbnail = itemView.findViewById(R.id.gambar_herbal);
}
}
public class herbalAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private final int VIEW_TYPE_ITEM=0,VIEW_TYPE_LOADING=1;
private loadMore loadMore;
boolean isLoading;
private Context mCtx;
List<herbalModel> herbalModelList;
int visibleThreshold=5;
int lastVisibleItem,totalItemCount;
public herbalAdapter(RecyclerView recyclerView,Context mCtx, List<herbalModel> herbalModelList) {
this.mCtx = mCtx;
this.herbalModelList = herbalModelList;
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager)recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
if (!isLoading && totalItemCount <= (lastVisibleItem+visibleThreshold))
{
if (loadMore != null)
loadMore.onLoadMore();
isLoading=true;
}
}
});
}
#Override
public int getItemViewType(int position) {
return herbalModelList.get(position) == null ? VIEW_TYPE_LOADING:VIEW_TYPE_ITEM;
}
public void setLoadMore(loadMore loadMore) {
this.loadMore = loadMore;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
if(i == VIEW_TYPE_ITEM)
{
CardView v = (CardView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.cardview_herbal, parent,false);
// View view =inflater.inflate(R.layout.cardview_herbal,null);
return new herbalViewHolder(v);
}
else if(i == VIEW_TYPE_LOADING)
{
View view = LayoutInflater.from(mCtx).inflate(R.layout.item_loading,parent,false);
return new LoadingViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
if (viewHolder instanceof herbalViewHolder)
{
herbalModel detailherbal =herbalModelList.get(i);
herbalViewHolder herbalViewHolder = (herbalViewHolder) viewHolder;
herbalViewHolder.namaHerbal.setText(detailherbal.getNama());
herbalViewHolder.khasiatHerbal.setText(detailherbal.getKhasiat());
Glide.with(mCtx)
.load(detailherbal.getThumbnail())
.into(herbalViewHolder.thumbnail);
final String idHerbal =detailherbal.getId();
herbalViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mCtx, detailHerbal.class);
i.putExtra("idHerbal", idHerbal);
mCtx.startActivity(i);
}
});
}
else if(viewHolder instanceof LoadingViewHolder)
{
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) viewHolder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return herbalModelList.size();
}
public void setLoaded() {
isLoading = false;
}
public void filterlist (ArrayList<herbalModel> filteredList)
{
herbalModelList =filteredList;
notifyDataSetChanged();
}
}
this is the main activity for displaying recyclerview
private void get10Data() {
String url ="https://jsonplaceholder.typicode.com/photos";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG,"Onresponse"+jsonArray.toString());
for(int i = 0; i < 10; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.d(TAG,"jsonobject"+jsonObject);
herbalModels.add(
new herbalModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("albumId"),
jsonObject.getString("id"),
jsonObject.getString("thumbnailUrl")
)
);
}
catch(JSONException e) {
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG,"Onerror"+volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_herbal, container, false);
herbalModels = new ArrayList<>();
RequestQueue queue = MySingleton.getInstance(this.getActivity().getApplicationContext()).getRequestQueue();
get10Data();
sortData(rootView);
StartRecyclerView(rootView);
return rootView ;
}
private void StartRecyclerView(View rootView) {
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_herbal);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new herbalAdapter(recyclerView,getActivity(),herbalModels);
recyclerView.setAdapter(adapter);
//set loaded more event
adapter.setLoadMore(new loadMore() {
#Override
public void onLoadMore() {
if (herbalModels.size() <= 20)
{
herbalModels.add(null);
adapter.notifyItemInserted(herbalModels.size()-1);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
herbalModels.remove(herbalModels.size()-1);
adapter.notifyItemRemoved(herbalModels.size());
final int index = herbalModels.size();
final int end = index+10;
String url ="https://jsonplaceholder.typicode.com/photos";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG,"Onresponse"+jsonArray.toString());
for(int i = index; i < end; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.d(TAG,"jsonobject"+jsonObject);
herbalModels.add(
new herbalModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("albumId"),
jsonObject.getString("id"),
jsonObject.getString("thumbnailUrl")
)
);
}
catch(JSONException e) {
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG,"Onerror"+volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
adapter.notifyDataSetChanged();
adapter.setLoaded();
}
},5000);
}
}
});
}
I was following this tutorial to implement pagination, and I was following it keenly, but I am uncertain how I should modify my current activity to implement OnLoadMoreListener. I am using an ApiService from retrofit to load data, unlike the tutorial that generates random strings.
This is how my current RecyclerView adapter looks like:
public class CuratedSectionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static int VIEW_TYPE_HEADER = 0;
private static int VIEW_TYPE_ITEM = 1;
private static int VIEW_TYPE_LOADING = 2;
private int lastVisibleItem, totalItemCount;
private int visibleThreshold = 2;
private boolean isLoading;
private List<Object> itemList;
private OnLoadMoreListener onLoadMoreListener;
public CuratedSectionAdapter(RecyclerView recyclerView, List<Object> itemList) {
this.itemList = itemList;
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 (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
});
}
private class ItemViewHolder extends RecyclerView.ViewHolder {
RecyclerView itemRecyclerView;
CuratedSectionNestedAdapter nestedAdapter;
LinearLayoutManager layoutManager;
ItemViewHolder(View view) {
super(view);
itemRecyclerView = view.findViewById(R.id.recyclerView_nested);
layoutManager = new LinearLayoutManager(view.getContext(), LinearLayoutManager.HORIZONTAL, false);
}
}
private class HeaderViewHolder extends RecyclerView.ViewHolder {
TextView textViewHeader;
Typeface montserratMedium = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/Montserrat-Medium.ttf");
HeaderViewHolder(View view) {
super(view);
textViewHeader = view.findViewById(R.id.textView_header);
textViewHeader.setTypeface(montserratMedium);
}
}
private class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public LoadingViewHolder(View view) {
super(view);
progressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder.getItemViewType() == VIEW_TYPE_HEADER) {
HeaderViewHolder viewHolder = (HeaderViewHolder) holder;
CuratedSectionHeader header = (CuratedSectionHeader) itemList.get(position);
viewHolder.textViewHeader.setText(header.getHeaderName());
} else if (holder.getItemViewType() == VIEW_TYPE_ITEM) {
ItemViewHolder viewHolder = (ItemViewHolder) holder;
List<CuratedSectionItem> items = (List<CuratedSectionItem>) itemList.get(position);
if (viewHolder.nestedAdapter != null) {
viewHolder.nestedAdapter.setItems(items);
} else {
viewHolder.nestedAdapter = new CuratedSectionNestedAdapter(items);
viewHolder.itemRecyclerView.setLayoutManager(viewHolder.layoutManager);
viewHolder.itemRecyclerView.setAdapter(viewHolder.nestedAdapter);
}
} else if (holder.getItemViewType() == VIEW_TYPE_LOADING) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_HEADER) {
return new HeaderViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.main_explore_header_row, parent, false));
} else if (viewType == VIEW_TYPE_ITEM) {
return new ItemViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.main_explore_row, parent, false));
} else if (viewType == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_loading, parent, false);
return new LoadingViewHolder(view);
}
throw new RuntimeException("Adapter " + viewType + "not found");
}
#Override
public int getItemCount() {
return itemList.size();
}
#Override
public int getItemViewType(int position) {
if (itemList.get(position) instanceof CuratedSectionHeader) {
return VIEW_TYPE_HEADER;
} else {
return itemList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
}
public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.onLoadMoreListener = mOnLoadMoreListener;
}
public void setLoaded() {
isLoading = false;
}
}
The current architecture of my activity uses private classes to make API calls and load the data. At the moment, all items are loaded at once, but ideally there should be only 2 items loaded at a time. I am uncertain how I should load additional items by calling the API service again when I scroll to the bottom. At the very least, I am certain that I will have to use curatedSectionAdapter.setOnLoadMoreListener somehow.
This is how I load all of the items at the moment:
private class Sections {
List<CuratedSection> sections = new ArrayList<>();
public Thread[] thread;
private Sections() {}
public void setSections(ArrayList<CuratedSection> sections) {
this.sections = sections;
}
public void setSectionStories(String sectionId, List<CuratedSectionItem> stories) {
for(CuratedSection s : sections){
if(s.id != null && s.id.equals(sectionId)) {
s.stories = stories;
}
}
}
public void loadStories(String sessionKey) {
thread = new Thread[sections.size()];
for( int s = 0; s < sections.size(); s++) {
thread[s] = new Thread(new LoadStories(sessionKey, sections.get(s)));
thread[s].start();
}
for( int f = 0; f < sections.size(); f++) {
try {
thread[f].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
recyclerView.setLayoutManager(layoutManager);
curatedSectionAdapter = new CuratedSectionAdapter(recyclerView, this.getAdapterInfo());
recyclerView.setAdapter(curatedSectionAdapter);
}
public void loadSections(int numSections) {
swipeRefreshLayout.setRefreshing(false);
LoadSections load = new LoadSections(numSections);
load.run();
}
public List<Object> getAdapterInfo() {
List<Object> list = new ArrayList<>();
for (int i = 0; i < sections.size(); i++) {
CuratedSection section = sections.get(i);
CuratedSectionHeader header = new CuratedSectionHeader();
header.setHeaderName(section.header);
list.add(header);
list.add(section.stories);
}
return list;
}
}
private class LoadSections implements Runnable {
int numSections;
LoadSections(int numSections) {
this.numSections = numSections;
}
#Override
public void run() {
SharedPreferences prefs = getSharedPreferences("user_session", MODE_PRIVATE);
final String sessionKey = prefs.getString("session_key", null);
Call<JsonArray> call;
call = TravelersApi.endpoint().getCuratedSections(sessionKey);
call.enqueue(new Callback<JsonArray>() {
#Override
public void onResponse(Call<JsonArray> call, Response<JsonArray> response) {
if(response.code() != 200) {
Toast.makeText(getApplicationContext(), "Cannot load page as of the moment.", Toast.LENGTH_SHORT).show();
return;
}
JsonArray rawSections = response.body();
if(rawSections.size() == 0) {
//TODO: show placeholder
return;
}
ArrayList<CuratedSection> sections = new ArrayList<>();
for(int i = 0; i < numSections; i++) {
JsonObject jSection = rawSections.get(i).getAsJsonObject();
final CuratedSection section = new CuratedSection();
section.id = jSection.get("id").getAsString();
section.header = jSection.get("section_header").getAsString();
section.topicCount = jSection.get("topic_count").getAsInt();
section.isShown = jSection.get("is_shown").getAsBoolean();
section.stories = new ArrayList<>();
sections.add(section);
}
curated.setSections(sections);
curated.loadStories(sessionKey);
spinner.clearAnimation();
spinner.setVisibility(View.GONE);
header.setVisibility(View.VISIBLE);
swipeRefreshLayout.setVisibility(View.VISIBLE);
}
#Override
public void onFailure(Call<JsonArray> call, Throwable t) {
Log.d("ERROR!", t.toString());
t.printStackTrace();
}
});
}
}
You can achieve this by directly setting scroll listener to your recycler view.
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 (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
// Call Load more method here to load next page data
// Prevent multiple calls by using a boolean
isLoading=true; // boolean to Prevent multiple calls
}
}
});
OnLoadMoreListener is a interface you need to register it first.
For pagination your server should process the pagination count. So you also need the api to perform on page limit .
I try to downloading image from server with volley and show them in recyclerview.
it is work correctly but the downloading image is very low.
(the size of each image approximately 50 kb).
what can i do?
is there better and optimize code than it?
this is my helper class:
public class StartActivity {
// for recyclerView - downLoad Data
private static final int LIMIT = 6;
OnLoadMoreListener onLoadMoreListener;
int idImage = 1;
private List<StructUser> structList = new ArrayList<>();
private AdapterUser adapter;
private int CURRENT_ITEM = 1;
private Context context;
private String TAG = StartActivity.class.getSimpleName();
//----------------------------------------------------
public StartActivity(Context context) {
this.context = context;
}
public void getDataAndSetInRecyclerView(RecyclerView recyclerView) {
loadData(CURRENT_ITEM);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
adapter = new AdapterUser(recyclerView, structList, context);
onLoadMoreListener = new OnLoadMoreListener() {
#Override
public void onLoadMore() {
structList.add(null);
adapter.notifyDataSetChanged();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
structList.remove(structList.size() - 1);
// adapter.notifyItemRemoved(structList.size());
loadData(CURRENT_ITEM);
}
}, 2000);
}
};
adapter.setOnLoadMoreListener(onLoadMoreListener);
recyclerView.setAdapter(adapter);
}
private void loadData(final int CURRENT_ITEM) {
String url = Config.DATA_URL + CURRENT_ITEM;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ActivityMain.hideProgressBar();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
StructUser structUser = new StructUser();
if (!jsonObject.isNull(Config.TAG_TITLE))
structUser.setNetworkImageView(jsonObject.getString(Config.TAG_TITLE));
if (!jsonObject.isNull(Config.TAG_IMAGE_URL)) {
structUser.setNetworkImageView(Config.IMG_SERVER + idImage + ".png");
idImage++;
}
structList.add(structUser);
}
adapter.notifyDataSetChanged();
adapter.setLoaded();
// not show progressBar at end of list when get all data
if (response.toString().contains("[]")) {
adapter.reachEndList();
Toast.makeText(context, "not More Data to Show", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// hide progressBar
ActivityMain.hideProgressBar();
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(context,
error.getMessage(), Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(jsonArrayRequest, TAG);
this.CURRENT_ITEM = this.CURRENT_ITEM + LIMIT;
}
}
this is my adapter:
public class AdapterUser extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
public int visibleThreshold = 2;
boolean isLoading;
private int lastVisibleItem, totalItemCount;
private List<StructUser> structList = new ArrayList<>();
private OnLoadMoreListener mOnLoadMoreListener;
private Context context;
// load image from server -------------------------------------------------
private static ImageLoader imageLoader = ImageLoader.getInstance();
public static DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.mipmap.ic_cloud_download)
.showImageForEmptyUri(R.mipmap.ic_picture)
.showImageOnFail(android.R.drawable.ic_dialog_alert)
.cacheInMemory(true)
.cacheOnDisk(false)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
//---------------------------------------------------------------
public AdapterUser(RecyclerView mRecyclerView, List<StructUser> structList, Context context) {
this.context = context;
this.structList = structList;
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
mRecyclerView.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 (!isLoading && totalItemCount <= visibleThreshold + (lastVisibleItem)) {
if (mOnLoadMoreListener != null) {
mOnLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
});
}
public void setLoaded() {
isLoading = false;
}
public void reachEndList() {
isLoading = true;
}
//========================================================
#Override
public int getItemViewType(int position) {
return structList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.adapter_start_activity , viewGroup, false);
return new UserViewHolder(view);
} else if (viewType == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_loading_item, viewGroup, false);
return new LoadingViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof UserViewHolder) {
UserViewHolder userViewHolder = (UserViewHolder) holder;
StructUser user = structList.get(position);
userViewHolder.title.setText(user.getTitle());
// load image from server
imageLoader.displayImage(user.getNetworkImageView(), userViewHolder.networkImageView, options);
} else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return structList == null ? 0 : structList.size();
}
public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.mOnLoadMoreListener = mOnLoadMoreListener;
}
class UserViewHolder extends RecyclerView.ViewHolder {
public TextView title;
// for download & cash image
public ImageView networkImageView;
public UserViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.txtTitle);
networkImageView = (ImageView) itemView.findViewById(R.id.networkImageView);
}
}
class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public LoadingViewHolder(View itemView) {
super(itemView);
progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
}
}
}
Use Glide for downloading Image...
Glide.with(ActivityName.this)
.load(image_url)
.into(imageView_object);
It will download image and set in ImageView.
I am loading items into a recyclerview from the server using JSON, maintaining an Adapter class to set data by hashmap method. I am using pagination for the recyclerView. Each page contains 10 items and the page increments after 10 items are reached.
The issue is that, after loaded, it's not refreshing when the users click the items.
HomeClass is a launcher activity:
public class HomeClass extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
sendID(url);
}
public void sendID(final String url){
if (progress == null) {
progress = new ProgressDialog(this);
progress.show();
}
Constant.Home_Posts.clear();
new Thread(new Runnable(){
#Override
public void run() {
///pagecount is 1 in HomeClass by default
JSONObject responseObj = new JSONObject(arg0);
HashMap<String, String> map = new HashMap<String, String>();
map.put(key,value);
Constant.Home_Posts.add(map);
}
}
if (progress!=null) {
if (progress.isShowing()) {
progress.dismiss();
progress = null;
Intent intent = new Intent(HomeClass.this, Home.class);
startActivity(intent);
finish();
}
}
The second class, Home, only contais onBindViewHolder
public class Home extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
}
private void getPostCount(final String URl) {
if (progress == null) {
progress = new ProgressDialog(this);
progress.show();
}
new Thread(new Runnable() {
#Override
public void run() {
viewposition = viewposition + 10;
getPostUrl = "url+userid="+ userID+ "&page="+ page_count;
//pagecount is 2 in 'Home' by default and then icrements
JSONObject responseObj = new JSONObject(arg0);
HashMap<String, String> map = new HashMap<String, String>();
map.put(key,value);
Constant.Home_Posts.add(map);
'
'
}
}
}
page_count++;
Adapter Class:
class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public void onBindViewHolder(RecyclerView.ViewHolder holder,final int i) {
if (Constant.Home_Posts.size() - 1 == i) {
Constant.Home_Posts.clear();
getPostCount("url+ userID + "&page=" + page_count);
}
//set value using hashmap method from server
viewHolder.imgComment.setText(value) //with integer values
//OmCLick to update datas from user
viewHolder.imgComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get layout view by LayoutIflater and load data from server
// create alert dialog
final AlertDialog alertDialog = alertDialogBuilder.create();
//user can comment anyhting,if success comment value in count
//should increment or comments should not change
sendComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (commentStatus == 0) {
} else {
alertDialog.cancel();
String putLikesValue=(Integer.toString(Integer.parseInt(
Constant.Home_Posts.get(i).get("comments_count"))+1));
viewHolder.txtComment.setText(putLikesValue+"Comments");
notifyDataSetChanged();
notifyItemChanged(i);
});
}
The result is like,
the old items are listing with the updated item (newly inserted item).
How do I insert the item with position properly?
Hello use this for load all data.
public FriendsAdapterSwipe(List<FriendListModel> alFriendListModel,RecyclerView recyclerView,Context context)
{
this.alFriendListModel = alFriendListModel;
this.context=context;
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)) {
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
if (viewType == VIEW_ITEM)
{
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.raw_friends_swipe, parent, false);
vh = new CustomViewHolder(itemView);
} else
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.progressbar_item, parent, false);
vh = new ProgressViewHolder(v);
}
return vh;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
if (holder instanceof CustomViewHolder)
{
Typeface AvenirNextRegular = Fonts.AvenirNextRegular(context);
holder.setIsRecyclable(false);
FriendListModel model = alFriendListModel.get(position);
((CustomViewHolder) holder).txtUname.setText(model.getFullName());
((CustomViewHolder) holder).txtUname.setTypeface(AvenirNextRegular);
if (alFriendListModel.get(position).getIsImageAvaible().equalsIgnoreCase("1"))
{
Glide.clear(((CustomViewHolder) holder).imgProfile);
Glide.with(context).load(WebField.PROFILE_URL + alFriendListModel.get(position).getFriendId()
+ "_small.png").asBitmap()
.placeholder(R.drawable.user_pic).skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.ALL).
fitCenter().into(new BitmapImageViewTarget(((CustomViewHolder) holder).imgProfile)
{
#Override
protected void setResource(Bitmap resource)
{
Drawable d = new BitmapDrawable(context.getResources(), resource);
((CustomViewHolder) holder).imgProfile.setImageDrawable(d);
}
});
}
}
else
{
((CustomViewHolder) holder).imgProfile.setImageResource(R.drawable.user_pic);
}
}
#Override
public int getItemCount() {
return alFriendListModel.size();
}
#Override
public int getItemViewType(int position) {
return alFriendListModel.get(position) != null ? VIEW_ITEM : VIEW_PROG;
}
public interface OnLoadMoreListener {
void onLoadMore();
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
public static class CustomViewHolder extends RecyclerView.ViewHolder
{
TextView txtUname;
CircularImageView imgProfile;;
public CustomViewHolder(View itemView) {
super(itemView);
txtUname = (TextView) itemView.findViewById(R.id.txtUname);
imgProfile = (CircularImageView) itemView.findViewById(R.id.imgProfile);
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar);
}
}
public void setLoaded() {
loading = false;
}
You can use loader for set data based on page.
public EventAdapter(final List<EventsModel> myDataSet, RecyclerView recyclerView, Context context) {
mDataset = myDataSet;
this.context = context;
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 mDataset.get(position) != null ? VIEW_ITEM : VIEW_PROG;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
if (viewType == VIEW_ITEM) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.raw_eventlist, parent, false);
itemView.setOnClickListener(EventFragment.myOnClickListener);
vh = new TextViewHolder(itemView);
} else {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.progressbar_item, parent, false);
vh = new ProgressViewHolder(v);
}
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof TextViewHolder) {
Typeface AvenirNextRegular = Fonts.AvenirNextRegular(context);
((TextViewHolder) holder).txtEventName.setTypeface(AvenirNextRegular);
((TextViewHolder) holder).txtEventDescription.setTypeface(AvenirNextRegular);
((TextViewHolder) holder).txtDate.setTypeface(AvenirNextRegular);
((TextViewHolder) holder).txtTime.setTypeface(AvenirNextRegular);
((TextViewHolder) holder).txtEventName.setText(mDataset.get(position).getStrEventName());
((TextViewHolder) holder).txtEventDescription.setText(mDataset.get(position).getStrDescription());
((TextViewHolder) holder).txtDate.setText(mDataset.get(position).getStrStartDate());
((TextViewHolder) holder).txtTime.setText(mDataset.get(position).getStrStartTime());
final RecyclerView.ViewHolder tempHolder = holder;
String eventId = mDataset.get(position).getStrEventId();
if (mDataset.get(position).getIsImageAvailable().equalsIgnoreCase("1"))
{
Glide.clear(((TextViewHolder) holder).imgProfile);
Glide.with(context).load(WebField.EVENT_URL + eventId + "_small.png").asBitmap()
.placeholder(R.drawable.event_img).skipMemoryCache(true).
diskCacheStrategy(DiskCacheStrategy.ALL).fitCenter()
.into(new BitmapImageViewTarget(((TextViewHolder) holder).imgProfile) {
#Override
protected void setResource(Bitmap resource) {
Drawable d = new BitmapDrawable(context.getResources(), resource);
((TextViewHolder) tempHolder).imgProfile.setImageDrawable(d);
}
});
}
else
{
((TextViewHolder) holder).imgProfile.setImageResource(R.drawable.event_img);
}
}
}
public void setLoaded() {
loading = false;
}
#Override
public int getItemCount() {
return mDataset.size();
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
public interface OnLoadMoreListener {
void onLoadMore();
}
public static class TextViewHolder extends RecyclerView.ViewHolder {
CircularImageView imgProfile;
TextView txtEventName;
TextView txtEventDescription;
TextView txtDate;
TextView txtTime;
ImageView btnNext;
public TextViewHolder(View view) {
super(view);
this.imgProfile = (CircularImageView) view.findViewById(R.id.imgProfile);
this.txtEventName = (TextView) view.findViewById(R.id.txtEventName);
this.txtEventDescription = (TextView) view.findViewById(R.id.txtEventDescription);
this.txtDate = (TextView) view.findViewById(R.id.txtDate);
this.txtTime = (TextView) view.findViewById(R.id.txtTime);
this.btnNext = (ImageView) view.findViewById(R.id.btnNext);
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar);
progressBar.getIndeterminateDrawable().setColorFilter(Color.BLUE, PorterDuff.Mode.MULTIPLY);
}
}