Can't add footerView in RecyclerView - android

I'm trying to add my custom footerView in RecyclerView.I wrote adapter source ,but i can't show my footerView.This is my source
private List<Transaction> transactionList;
public Context mContext;
private boolean loading;
private static final int TYPE_ITEM = 1;
private static final int TYPE_FOOTER = 2;
public void setmOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.mOnLoadMoreListener = mOnLoadMoreListener;
}
private OnLoadMoreListener mOnLoadMoreListener;
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
public void setLoaded() {
loading = false;
}
class LoadingViewHolder extends RecyclerView.ViewHolder {
public MaterialProgressBar progressBar;
public LoadingViewHolder(View itemView) {
super(itemView);
progressBar = (MaterialProgressBar) itemView.findViewById(R.id.progressBar);
}
}
public class TransactionHolder extends RecyclerView.ViewHolder {
private TextView transactionName, transactionStatus;
public TransactionHolder(View view) {
super(view);
transactionName = (TextView) view.findViewById(R.id.u_transaction_name);
transactionStatus = (TextView) view.findViewById(R.id.u_transaction_status);
}
}
public TransactionRecyclerViewAdapter(List<Transaction> transactions, Context context, RecyclerView recyclerView) {
super();
this.transactionList = transactions;
this.mContext = 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 (mOnLoadMoreListener != null) {
mOnLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public int getItemViewType(int position) {
if (isPositionFooter(position)) {
return TYPE_FOOTER;
}
return TYPE_ITEM;
}
private boolean isPositionFooter(int position) {
return position == transactionList.size();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_FOOTER) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_loading, parent, false);
return new TransactionRecyclerViewAdapter.LoadingViewHolder(v);
} else if (viewType == TYPE_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_transaction_recycler_item, parent, false);
return new TransactionRecyclerViewAdapter.TransactionHolder(v);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof TransactionHolder) {
TransactionHolder transactionHolder = (TransactionHolder) holder;
Transaction transaction = transactionList.get(position);
if (transaction != null) {
transaction.setAmount(transaction.getAmount().replace("-", ""));
transactionHolder.transactionName.setText(transaction.getName());
transactionHolder.transactionStatus.setText(transaction.getType());
}
} else {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setVisibility(View.VISIBLE);
}
}
#Override
public int getItemCount() {
return transactionList == null ? 0 : transactionList.size();
}
public Transaction getItem(int position) {
return transactionList.get(position);
}
}
and i use my adapter like this
final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);
mTransactionAdapter = new TransactionRecyclerViewAdapter(mTransactionList, getActivity(), mRecyclerView);
mRecyclerView.setAdapter(mTransactionAdapter);
mTransactionAdapter.notifyDataSetChanged();
how i can solve my problem? I don't know what is a wrong in my code

You need to increase count by 1
#Override
public int getItemCount() {
return transactionList == null ? 0 : transactionList.size()+1;
}

#Override
public int getItemCount() {
return transactionList == null ? 0 : transactionList.size();
}
You need to have transactionList.size() + 1 items. (Because you also have a footer).

Related

RecyclerView won't load data retrieved from Firestore into ItemView

So, basically what I am trying to do is to show a bunch of Post type objects on my Android app's feed (HomeFragment). The posts are being successfully retrieved from Firestore (I did check the debugger) but somehow, not all of them get loaded in the recyclerView. The itemViewHolder is only loaded with how I defined it as an XML, fields filled with lore Ipsum.
This would be my code:
HomeFragment:
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
private boolean isLoading = false;
private ArrayList<String> rowsArrayList = new ArrayList<>();
public static ArrayList<Post> appliedToList = new ArrayList<>();
private User currentUser = new User();
private View root;
private TextView userState;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private String userId = FirebaseAuth.getInstance().getCurrentUser() != null ? FirebaseAuth.getInstance().getCurrentUser().getUid() : null;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_home, container, false);
setState();
appliedToPostsRetrieverFromHomePage(getContext());
checkForPostFragment();
recyclerView = root.findViewById(R.id.recyclerView);
initAdapter();
initScrollListener();
return root;
}
private void initAdapter() {
recyclerViewAdapter = new RecyclerViewAdapter(getActivity(), 2);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
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);
}
#Override
public void onAttachFragment(#NonNull Fragment fragment) {
super.onAttachFragment(fragment);
}
RecyclerViewAdapter:
All view types represent kind of the same layout, the only difference between them is what is wrote on a certain button. Remember, some of the posts are successfully loaded!
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int VIEW_TYPE_APPLY = 0;
private final int VIEW_TYPE_MORE = 1;
private final int VIEW_TYPE_BEGIN = 2;
private final int VIEW_TYPE_PENDING = 3;
private final int VIEW_TYPE_END = 4;
private final int VIEW_TYPE_ON_GOING = 5;
private final int VIEW_TYPE_LOADING = 6;
private ArrayList<Post> list = new ArrayList();
private static final String TAG = RecyclerViewAdapter.class.getSimpleName();
private Context context;
private User currentUser;
private int recyclerType;
static ArrayList<User> applicantsList = new ArrayList<>();
private String userId = FirebaseAuth.getInstance().getCurrentUser() != null ? FirebaseAuth.getInstance().getCurrentUser().getUid() : null;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
public RecyclerViewAdapter(Context context, int recyclerType) {
this.context = context;
this.recyclerType = recyclerType;
if (recyclerType == 0) {
myPostsRetriever(context);
} else if (recyclerType == 1) {
appliedToPostsRetriever(context);
} else if (recyclerType == 2) {
homePostsRetriever(context);
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_APPLY) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_apply, parent, false);
return new ItemViewHolder(view);
} else if (viewType == VIEW_TYPE_MORE) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_more, parent, false);
return new LoadingViewHolder(view);
} else if (viewType == VIEW_TYPE_BEGIN) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_begin, parent, false);
return new LoadingViewHolder(view);
} else if (viewType == VIEW_TYPE_PENDING) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_pending, parent, false);
return new LoadingViewHolder(view);
} else if (viewType == VIEW_TYPE_END) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_end, parent, false);
return new LoadingViewHolder(view);
} else if (viewType == VIEW_TYPE_ON_GOING) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_on_going, parent, false);
return new LoadingViewHolder(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 list == null ? 0 : list.size();
}
#Override
public int getItemViewType(int position) {
if (list.get(position) != null) {
if (!list.get(position).getOwner().equals(userId) &&
!checkIfAlreadyAppliedToPost(position) &&
list.get(position).getMinNeededPersons() >= list.get(position).getApplicants()) {
return VIEW_TYPE_APPLY;
} else if (recyclerType == 1) {
return VIEW_TYPE_MORE;
} else if (list.get(position).getOwner().equals(userId) && timeCheck(list.get(position))) {
return VIEW_TYPE_BEGIN;
} else if (list.get(position).getOwner().equals(userId) && checkIfStarted(position)
|| !list.get(position).getOwner().equals(userId) && checkIfAlreadyAppliedToPost(position) && !checkIfStarted(position)) {
return VIEW_TYPE_PENDING;
} else if (list.get(position).getOwner().equals(userId) && checkIfStarted(position)) {
return VIEW_TYPE_END;
} else if (!list.get(position).getOwner().equals(userId) && checkIfStarted(position)){
return VIEW_TYPE_ON_GOING;
}else if (list.get(position).getOwner().equals(userId))
return VIEW_TYPE_MORE;
}
return VIEW_TYPE_LOADING;
}
private class ItemViewHolder extends RecyclerView.ViewHolder {
TextView title;
TextView description;
TextView location;
TextView minNeededPersons;
TextView maxNeededPersons;
TextView reward;
TextView time;
CheckBox physical;
Button button;
ItemViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.postTitle);
description = itemView.findViewById(R.id.postDescription);
location = itemView.findViewById(R.id.postLocationText);
time = itemView.findViewById((R.id.postDateAndTime));
minNeededPersons = itemView.findViewById(R.id.people);
maxNeededPersons = itemView.findViewById(R.id.people);
reward = itemView.findViewById(R.id.reward);
physical = itemView.findViewById(R.id.checkBox2);
button = itemView.findViewById(R.id.applyButton);
}
}
private class LoadingViewHolder extends RecyclerView.ViewHolder {
ProgressBar progressBar;
LoadingViewHolder(#NonNull View itemView) {
super(itemView);
progressBar = itemView.findViewById(R.id.progressBar);
}
}
private void showLoadingView(LoadingViewHolder viewHolder, int position) {
}
private void populateItemRows(ItemViewHolder viewHolder, int position) {
Post item = list.get(position);
viewHolder.title.setText(item.getTheTitle());
viewHolder.description.setText(item.getDescription());
viewHolder.location.setText(item.getLocation());
viewHolder.location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent showLocation = new Intent(context, MapsActivity.class);
context.startActivity(showLocation);
}
});
viewHolder.minNeededPersons.setText(String.valueOf(item.getMinNeededPersons()));
viewHolder.maxNeededPersons.setText(String.valueOf(item.getMaxPersonsNeeded()));
viewHolder.reward.setText(String.valueOf(item.getReward()));
viewHolder.physical.setChecked(item.isPhysical());
Date timeAndDate = item.getTime().toDate();
viewHolder.time.setText(new SimpleDateFormat("HH:mm dd.MM.yyyy").format(timeAndDate));
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
if (viewHolder.button.getText().equals(context.getResources().getString(R.string.apply))) {
onApplyTapped(position);
viewHolder.button.setText(R.string.pending);
viewHolder.button.setBackgroundColor(Color.parseColor("#F2CF59"));
viewHolder.button.setClickable(false);
} else if (viewHolder.button.getText().equals(context.getResources().getString(R.string.begin_job))) {
onBeginTapped(position);
viewHolder.button.setText(R.string.end_job);
viewHolder.button.setBackgroundColor(Color.parseColor("#F8CA9D"));
} else if (viewHolder.button.getText().equals(context.getResources().getString(R.string.end_job))) {
onEndTapped(position);
viewHolder.button.setBackgroundColor(Color.parseColor("#FB8E7E"));
viewHolder.button.setClickable(false);
viewHolder.button.setText(R.string.finished);
}
}
});
viewHolder.itemView.findViewById(R.id.seePostButton).setOnClickListener(new View.OnClickListener()
{ not relevant }
private void homePostsRetriever(Context context) {
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
rootRef.collectionGroup("posts").limit(10).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot documentSnapshots) {
for (DocumentSnapshot documentSnapshot : documentSnapshots.getDocuments()) {
Post post = new Post();
post.setAvailability(documentSnapshot.getBoolean("available"));
post.setTitle(documentSnapshot.getString("title"));
post.setDescription(documentSnapshot.getString("description"));
post.setLocation(documentSnapshot.getString("location"));
post.setApplicants(documentSnapshot.getLong("applicants").intValue());
post.setOwner(documentSnapshot.getString("owner"));
post.setMinNeededPersons(documentSnapshot.getLong("minNrOfPeople").intValue());
post.setMaxPersonsNeeded(documentSnapshot.getLong("maxNrOfPeople").intValue());
post.setReward(Objects.requireNonNull(documentSnapshot.getLong("reward")).floatValue());
post.setPhysical(documentSnapshot.getBoolean("physicalExcertion"));
post.setTime(documentSnapshot.getTimestamp("time"));
post.setId(documentSnapshot.getId());
post.setStarted(documentSnapshot.getBoolean("started"));
list.add(post);
}
notifyDataSetChanged();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(context, "No document found", Toast.LENGTH_SHORT).show();
}
});
}
I don't think you are calling bind methods correctly, try:
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int position) {
if (viewHolder instanceof ItemViewHolder) {
ItemViewHolder holder = (ItemViewHolder)viewHolder;
holder.populateItemRows(holder, position);
} else if (viewHolder instanceof LoadingViewHolder) {
LoadingViewHolder holder = (LoadingViewHolder)viewHolder;
holder.showLoadingView(holder , position);
}
}
Also this method:
private void populateItemRows(ItemViewHolder viewHolder, int position) {
.....
....
....
}
Is not found in your ItemViewHolder class

Error while displaying items in RecyclerView with Multiple ViewTypes

I am using Recyclerview with multiple ViewTypes.I have two Model classes for two different type of item in recyclerview as.I want to display two different type of item in same RecyclerView
My RecyclerViewAdapter is
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
ArrayList<OneView> oneList;
ArrayList<TwoView> twoList;
public RecyclerAdapter(Context context,ArrayList<OneView> oneList,ArrayList<TwoView> twoList){
this.context=context;
this.oneList=oneList;
this.twoList=twoList;
}
#Override
public int getItemViewType(int position) {
switch (position){
case 0:
return 0;
case 1:
return 1;
}
return -1;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int layout=0;
RecyclerView.ViewHolder viewHolder;
if(viewType==0){
layout=R.layout.oneview;
View one= LayoutInflater.from(parent.getContext()).inflate(layout,parent,false);
return new ViewHolder(one);
}else if(viewType==1){
layout=R.layout.twoview;
View two= LayoutInflater.from(parent.getContext()).inflate(layout,parent,false);
return new SecondView(two);
}else {
return null;
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int viewType=holder.getItemViewType();
switch (viewType){
case 0:
OneView oneView=oneList.get(position);
((ViewHolder)holder).name.setText(oneView.getName());
break;
case 1:
TwoView twoView=twoList.get(position);
((SecondView)holder).name.setText(twoView.getName());
((SecondView)holder).address.setText(twoView.getAddress());
break;
default:
break;
}
}
#Override
public int getItemCount() {
return (this.oneList.size()+this.twoList.size());
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView name;
public ViewHolder(View itemView) {
super(itemView);
name=(TextView)itemView.findViewById(R.id.nameOne);
}
}
public class SecondView extends RecyclerView.ViewHolder {
private TextView name,address;
public SecondView(View itemView) {
super(itemView);
name=(TextView)itemView.findViewById(R.id.nameTwo);
address=(TextView)itemView.findViewById(R.id.address);
}
}
}
I want to display two type of item in same RecyclerView.But I am getting Attempt to write to field 'int android.support.v7.widget.RecyclerView$ViewHolder.mItemViewType' on a null object reference exception. How to resolve this ?
here is the complete example. I've used a RecyclerView with Multiple View Type. My scenario was, I have to show "cuisine list" [which is a horizontal view of multiple cuisines], then "number of restaurant", then "restaurant list".
so, i've used VIEW_RESTAURANT for restaurant view, VIEW_CUISINE for cuisine, VIEW_INFO for number of restaurant. As for my case, there's pagination, so VIEW_PROGRESS is used for showing progress bar at the bottom [by that time new set of data is fetch, if avaiable], VIEW_NO_DATA is used if restaurant list is empty.
hopefully from here, You can manage based on your requirement.
public class HomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private String TAG = HomeAdapter.class.getSimpleName();
class ViewType {
int VIEW_PROGRESS = 1;
int VIEW_NO_DATA = 2;
int VIEW_RESTAURANT = 3;
int VIEW_CUISINE = 4;
int VIEW_INFO = 6;
}
private ViewType mViewType = new ViewType();
private Context mContext;
private int mCuisineItem = 1;
private int mInfoItem = 1;
private int mShowNoItem = 0;
private boolean mIsLoading;
private int mRestaurantNumber;
private int mCurrentPage;
private List<Data> mDataList;
private List<CuisineData> mCuisines;
private PaginationListener mPaginationListener;
private HorizontalPaginationListener mHorizontalPaginationListener;
private SearchResultClickListener mSearchResultClickListener;
private String mFrom;
public HomeAdapter(Context context, List<Data> dataList, List<CuisineData> cuisines, RecyclerView recyclerView, SearchResultClickListener searchResultClickListener) {
mContext = context;
mDataList = dataList;
mCuisines = cuisines;
mSearchResultClickListener = searchResultClickListener;
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager llManager = (LinearLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visible_threshold = 1;
int total_item_count = llManager.getItemCount();
int last_visible_item = llManager.findLastVisibleItemPosition();
if (!mIsLoading && total_item_count <= (last_visible_item + visible_threshold)) {
if (mPaginationListener != null) mPaginationListener.onPagination();
mIsLoading = true;
}
}
});
}
}
public void setmPaginationListener(PaginationListener paginationListener) {
mPaginationListener = paginationListener;
}
public void setmHorizontalPaginationListener(HorizontalPaginationListener horizontalPaginationListener) {
mHorizontalPaginationListener = horizontalPaginationListener;
}
public void setLoaded() {
mIsLoading = false;
}
public void setmRestaurantNumber(int restaurantNumber) {
mRestaurantNumber = restaurantNumber;
}
public void setmCurrentPage(int currentPage) {
mCurrentPage = currentPage;
}
public void addCuisine(String from) {
mFrom = from;
notifyDataSetChanged();
}
public void addCuisines(List<CuisineData> cuisines, String from) {
mFrom = from;
mCuisines.clear();
mCuisines = cuisines;
notifyDataSetChanged();
}
public void addRestaurants(List<Data> dataList) {
mShowNoItem = 0;
if(mCurrentPage == 1) notifyItemChanged(1);
if (mCurrentPage == 1) notifyItemChanged(2);
int insert_index = mDataList.size();
int pos_start = insert_index + mCuisineItem + mInfoItem;
mDataList.addAll(insert_index, dataList);
notifyItemRangeInserted(pos_start, dataList.size());
}
public void removeRestaurants() {
mShowNoItem = 1;
mDataList.clear();
mDataList = new ArrayList<>();
notifyItemRangeRemoved(mCuisineItem + mInfoItem, mDataList.size());
notifyItemChanged(2);
}
public void addProgressBar(Data data) {
mDataList.add(data);
notifyItemInserted(getItemCount() - 1);
}
public void removeProgressBar() {
if (mDataList.size() > 0) {
mDataList.remove(mDataList.size() - 1);
notifyItemRemoved(mCuisineItem + mInfoItem + mDataList.size());
}
}
public void removeAll() {
mDataList.clear();
mCuisines.clear();
mShowNoItem = 0;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return mDataList.size() + mShowNoItem + mCuisineItem + mInfoItem;
}
#Override
public int getItemViewType(int position) {
if (position == 0) return mViewType.VIEW_CUISINE;
if (position == 1) return mViewType.VIEW_INFO;
return mShowNoItem == 0 ? (mDataList.get(position - (mCuisineItem + mInfoItem)) != null ? mViewType.VIEW_RESTAURANT : mViewType.VIEW_PROGRESS)
: mViewType.VIEW_NO_DATA;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == mViewType.VIEW_CUISINE) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_horizontal_cuisines, parent, false);
return new ViewHolderCuisinesList(mContext, view, mHorizontalPaginationListener);
}
if (viewType == mViewType.VIEW_INFO) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_restaurant_number, parent, false);
return new ViewHolderRestaurantNumber(mContext, view);
}
if (mShowNoItem == 0) {
if (viewType == mViewType.VIEW_RESTAURANT) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_item_nearest_restaurant, parent, false);
return new ViewHolderRestaurant(mContext, view, mSearchResultClickListener);
} else if (viewType == mViewType.VIEW_PROGRESS) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_progress, parent, false);
return new ViewHolderProgress(view);
}
} else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_empty, parent, false);
return new ViewHolderEmpty(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ViewHolderSearch) {
((ViewHolderSearch) holder).onBind();
}
if (holder instanceof ViewHolderCuisinesList) {
if (!TextUtils.isEmpty(mFrom)) {
if (mFrom.equalsIgnoreCase(AppConstants.CUISINES))
((ViewHolderCuisinesList) holder).onBind(mCuisines);
else if (mFrom.equalsIgnoreCase(AppConstants.CUISINE))
((ViewHolderCuisinesList) holder).onBind_();
}
}
if (holder instanceof ViewHolderRestaurantNumber) {
((ViewHolderRestaurantNumber) holder).onBind(mRestaurantNumber);
}
if (mShowNoItem == 0) {
if (holder instanceof ViewHolderRestaurant) {
((ViewHolderRestaurant) holder).onBind(position - (mCuisineItem + mInfoItem), mDataList.get(position - (mCuisineItem + mInfoItem)));
} else if (holder instanceof ViewHolderProgress) {
((ViewHolderProgress) holder).onBind();
}
} else {
if (holder instanceof ViewHolderEmpty) {
((ViewHolderEmpty) holder).onBind(mContext.getString(R.string.no_result_found));
}
}
}
}

Adding more items when scrolling to the bottom of a RecyclerView while using Retrofit

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 .

Updating dataset in recyclerview while scrolling sends the scroll to the top

Needless to say, I came across a lot of proposed solutions for this particular problem. I removed scrollListener and implemented it inside my fragment, I used notifyItemRangeInserted instead of notifyDataSetChanged. The thing is, none of those solutions did work for me...I'm displaying a set of youtube videos in my app. My dataset is indeed updated; thing is when I scroll downwards, at some point the scroll position moves to the top i.e the very first item of my dataset Here's a snippet of my activity :
private void setUpRecyclerView()
{
mRecyclerView.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(linearLayoutManager);
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 (!loading && totalItemCount <= (lastVisibleItem + visibleThreshold))
{
loadMorePosts();
loading = true;
}
}
});
initAdapter();
}
private void initAdapter()
{
adapter = new MyAdapter(mDataSet, getActivity());
mRecyclerView.setAdapter(adapter);
skeletonScreen = Skeleton.bind(mRecyclerView)
.adapter(adapter)
.shimmer(true)
.angle(30)
.duration(1200)
.count(10)
.load(R.layout.youtube_item)
.show();
}
private void loadVideos(final OnLoadPlayListCallback videosCallback, String pageToken)
{
Call<FullChannelPlayListData> mcallPlayList = mYouTubeService.getPlayList(
Tags.VALUE_SNIPPET,
20,
mPlayListId,
getActivity().getResources().getString(R.string.youtube_data_api_key),
pageToken
);
mcallPlayList.enqueue(new Callback<FullChannelPlayListData>() {
#Override
public void onResponse(Call<FullChannelPlayListData> call, Response<FullChannelPlayListData> response) {
if (response.code() == 200)
{
Log.d("FullPlayListSuccessful", response.message());
videosCallback.onSuccessfulRequest(response.body());
}
else Log.d("FullPlayListUnsuccess", response.message());
}
#Override
public void onFailure(Call<FullChannelPlayListData> call, Throwable t) {
videosCallback.onFailureRequest(t);
}
});
}
#Override
public void onSuccessfulRequest(FullChannelPlayListData fullChannelPlayListData)
{
Log.d(TAG, "onSuccessfulRequest Item size = "+ fullChannelPlayListData.getItems().size());
if (StringUtils.isNotEmpty(mNextPageToken))
removeFooter();
for (FullPlayListItems mItem: fullChannelPlayListData.getItems())
{
FullPlayListItems randomItem = getVideoFromDataSet(mItem.getSnippet().getResourceId().getVideoId(), mDataSet);
if (randomItem == null) {
mDataSet.add(mItem);
}
}
adapter.notifyItemRangeInserted(adapter.getItemCount(), mDataSet.size());
mRecyclerView.postDelayed(new Runnable() {
#Override
public void run() {
skeletonScreen.hide();
}
}, 2000);
mNextPageToken = fullChannelPlayListData.getNextPageToken();
setLoaded();
}
public void setLoaded() {
loading = false;
}
I could use really use some help...
UPDATE MyAdapter class
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
{
private List<FullPlayListItems> mDataSet;
private Context mActivity;
private static final int YOUTUBE_ITEM_VIEW_TYPE = 0;
private static final int PROGRESS_BAR_ITEM_VIEW_TYPE = 1;
public MyAdapter(List<FullPlayListItems> mDataSet, Context mActivity) {
this.mDataSet = mDataSet;
this.mActivity = mActivity;
}
public class ProgressViewHolder extends RecyclerView.ViewHolder
{
#BindView(R.id.pBarLoadMorePosts)
ProgressBar pBarLoadMore;
public ProgressViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
#Override
public int getItemViewType(int position) {
return mDataSet.get(position) != null ? YOUTUBE_ITEM_VIEW_TYPE : PROGRESS_BAR_ITEM_VIEW_TYPE;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
RecyclerView.ViewHolder viewHolder;
if (viewType == PROGRESS_BAR_ITEM_VIEW_TYPE)
{
View pBarLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.footer_loader, parent, false);
viewHolder = new ProgressViewHolder(pBarLayoutView);
}
else
{
View postItemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.youtube_item, parent, false);
viewHolder = new YoutubeItemViewHolder(postItemLayoutView);
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
int viewType = getItemViewType(position);
FullPlayListItems mVideoItem = mDataSet.get(position);
switch (viewType)
{
case PROGRESS_BAR_ITEM_VIEW_TYPE:
ProgressViewHolder progressViewHolder = (ProgressViewHolder) holder;
progressViewHolder.pBarLoadMore.getIndeterminateDrawable().setColorFilter(CoreApplication.getRes().getColor(R.color.colorPrimary), PorterDuff.Mode.SRC_IN);
break;
case YOUTUBE_ITEM_VIEW_TYPE:
default:
YoutubeItemViewHolder youtubeItemViewHolder = (YoutubeItemViewHolder) holder;
youtubeItemViewHolder.mVideoTitle.setText(mVideoItem.getSnippet().getTitle());
youtubeItemViewHolder.sdvYoutubeThumbnail.setImageURI(Uri.parse(mVideoItem.getSnippet().getThumbnails().getHigh().getUrl()));
}
}
#Override
public int getItemCount() {
return mDataSet != null ? mDataSet.size() : 0;
}
public class YoutubeItemViewHolder extends RecyclerView.ViewHolder
{
TextView mVideoTitle;
SimpleDraweeView sdvYoutubeThumbnail;
public YoutubeItemViewHolder(View itemView)
{
super(itemView);
mVideoTitle = (TextView)itemView.findViewById(R.id.tv_video_title);
sdvYoutubeThumbnail = (SimpleDraweeView)itemView.findViewById(R.id.sdv_thumbnail);
}
}
}
And here is my onViewCreated:
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mPlayListId = getArguments().getString(Tags.YT_CHANNEL_PLAYLIST_ID);
setUpRecyclerView();
// Like I said initially mNextPageToken is empty
loadVideos(this, mNextPageToken);
}
Just notify the data change in the onSuccessfulRequest() method.
adapter.notifyDataSetChanged();
I don't know this answer is helpful to you. anyway please try,
Add this method to your MyAdapter
public void addItem(VideoSectionsActivity item){
mDataSet.add(item);
notifyItemInserted(mDataSet.size() - 1);
}
And change your onSuccessfulRequest()
#Override
public void onSuccessfulRequest(FullChannelPlayListData fullChannelPlayListData)
{
Log.d(TAG, "onSuccessfulRequest Item size = "+ fullChannelPlayListData.getItems().size());
if (StringUtils.isNotEmpty(mNextPageToken))
removeFooter();
for (FullPlayListItems mItem: fullChannelPlayListData.getItems())
{
FullPlayListItems randomItem = getVideoFromDataSet(mItem.getSnippet().getResourceId().getVideoId(), mDataSet);
if (randomItem == null) {
adapter.addItem(mItem);
}
}
mRecyclerView.postDelayed(new Runnable() {
#Override
public void run() {
skeletonScreen.hide();
}
}, 2000);
mNextPageToken = fullChannelPlayListData.getNextPageToken();
setLoaded();
}
Updated
And also rearrange your code in activity
private void setUpRecyclerView()
{
mRecyclerView.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(linearLayoutManager);
initAdapter();
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 (!loading && totalItemCount <= (lastVisibleItem + visibleThreshold))
{
loadMorePosts();
loading = true;
}
}
});
}

ClassCastException:MyViewHolder cannot be cast to ProgressViewHolder

Iam trying to implement Endless Infinite Scrolling with RecyclerView, but I am only getting all records and even not getting any progress while trying to scroll at bottom.
and see this my code
this is my News_Adapter
public class NewsAdapter extends RecyclerView.Adapter {
private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0;
private List<News> newsList;
private Context context;
// 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 NewsAdapter(List<News> newsList , RecyclerView recyclerView){
this.newsList = newsList;
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 void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
// When went to the end of the list, load more posts
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
if (linearLayoutManager.findLastVisibleItemPosition() >= linearLayoutManager.getItemCount() - 1) {
// Grow List
}
}
}
});
}
}
#Override
public int getItemViewType(int position){
//return newsList.get(position) instanceof News ? VIEW_ITEM : VIEW_PROG;
return (position >= newsList.size()) ? VIEW_PROG : VIEW_ITEM;
}
#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.news_list_row, parent, false);
vh = new MyViewHolder(v);
} else {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.progress_item, parent, false);
vh = new ProgressViewHolder(v);
}
return vh;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public ImageView image,nextArrowimage;
public TextView desc;
private News news;
public MyViewHolder(View view) {
super(view);
ProgressBar progressBar = null;
title = (TextView) view.findViewById(R.id.News_title);
image = (ImageView) view.findViewById(R.id.News_imageView);
nextArrowimage = (ImageView)view.findViewById(R.id.news_NextArrow);
desc = (TextView) view.findViewById(R.id.News_desc);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = news.getTitle();
String desc = news.getDesc();
String image = "http://bitstobyte.in/upload/"+news.getImage();
Intent intent = new Intent(context, News_Activity.class);
intent.putExtra("title", title);
intent.putExtra("desc",desc);
intent.putExtra("imageUrl", image);
context.startActivity(intent);
Toast.makeText(v.getContext(), "OnClick :" + news.getTitle() + " \n "+news.getImage(),Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder,int position){
//if (holder instanceof MyViewHolder) {
// if (getItemViewType(position)==VIEW_ITEM) {
if (newsList.get(position)!=null && getItemViewType(position)==VIEW_ITEM ) {
final News single_news= newsList.get(position);
((MyViewHolder) holder).title.setText(single_news.getTitle());
((MyViewHolder) holder).desc.setText(single_news.getDesc());
((MyViewHolder) holder).nextArrowimage.setImageResource(R.drawable.nextblackbutton);
context = ((MyViewHolder) holder).image.getContext();
Picasso.with(context).load("http://bitstobyte.in/upload/"+single_news.getImage()).placeholder(R.drawable.ic_favorite_white_24dp).error(R.drawable.ic_map_24dp).resize(100,100).into(((MyViewHolder) holder).image);
((MyViewHolder) holder).news= single_news;
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
}
}
public void setLoaded() {
loading = false;
}
#Override
public int getItemCount() {
return newsList.size()+1;
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = (ProgressBar)v.findViewById(R.id.progressBar1);
}
}
}
You are getting error at below line right ?
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
Can you tell why you have used two ViewHolders ?
FYI :You can't use two ViewHolder means can't extends two ViewHolder.
Just change this function:
#Override
public int getItemViewType(int position){
//return newsList.get(position) instanceof News ? VIEW_ITEM : VIEW_PROG;
return (position >= newsList.size() || newsList.get(position)==null) ? VIEW_PROG : VIEW_ITEM;
}
And
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder,int position){
if (getItemViewType(position)==VIEW_ITEM ) {
final News single_news= newsList.get(position);
((MyViewHolder) holder).title.setText(single_news.getTitle());
((MyViewHolder) holder).desc.setText(single_news.getDesc());
((MyViewHolder) holder).nextArrowimage.setImageResource(R.drawable.nextblackbutton);
context = ((MyViewHolder) holder).image.getContext();
Picasso.with(context).load("http://bitstobyte.in/upload/"+single_news.getImage()).placeholder(R.drawable.ic_favorite_white_24dp).error(R.drawable.ic_map_24dp).resize(100,100).into(((MyViewHolder) holder).image);
((MyViewHolder) holder).news= single_news;
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
}
}

Categories

Resources