Create an adapter object, find recycler view id to set adapter and then set layout manager. In scroll listener, unable to get correct LastVisibleItemPosition, it return -1 to me. findFirstVisibleItemPosition() also returning -1.
//Here is Adapter
public class CategoryProduct extends RecyclerView.Adapter<RecyclerView.ViewHolder>
`enter code here`{
private static final int ITEM = 0;
private static final int LOADING = 1;
public String vertical = "";
Context context;
private boolean isLoadingAdded = false;
private boolean retryPageLoad = false;
private List<com.example.it.camanagement.model.CategoryProduct> dataSet;
public CategoryProduct(ArrayList<com.example.it.camanagement.model.CategoryProduct> data, Context context, String vertical) {
this.dataSet = data;
this.context = context;
this.vertical = vertical;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case ITEM:
View viewLoading;
if (vertical.equals("vertical")) {
viewLoading = LayoutInflater.from(parent.getContext())
.inflate(R.layout.category_product_list, parent, false);
} else {
viewLoading = LayoutInflater.from(parent.getContext())
.inflate(R.layout.category_product_list_grid, parent, false);
}
viewHolder = new MyViewHolder(viewLoading);
break;
case LOADING:
View viewLoading1 = inflater.inflate(R.layout.item_progress, parent, false);
viewHolder = new LoadingVH(viewLoading1);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int listPosition) {
if (listPosition == dataSet.size() - 1) {
CategoryDetails categoryDetails = (CategoryDetails) context;
categoryDetails.onBottomReached(listPosition);
}
switch (getItemViewType(listPosition)) {
case ITEM:
final MyViewHolder myViewHolder = (MyViewHolder) holder;
TextView textViewName = myViewHolder.productName;
// TextView textViewVersion = holder.textViewVersion;
ImageView imageView = myViewHolder.productImage;
RatingBar productRating = myViewHolder.productRasting;
TextView productCost = myViewHolder.productCost;
TextView productDiscount = myViewHolder.productDistCount;
TextView productCOLOR = myViewHolder.productColor;
TextView productId = myViewHolder.product_id;
TextView productModel = myViewHolder.productModel;
TextView productQuantity = myViewHolder.productQuantity;
productModel.setText(dataSet.get(listPosition).getModel());
productQuantity.setText(dataSet.get(listPosition).getQuantity());
productId.setText(dataSet.get(listPosition).getProduct_id());
textViewName.setText(dataSet.get(listPosition).getName());
Glide.with(context).load(dataSet.get(listPosition).getImage()).into(imageView);
productRating.setRating(Float.parseFloat(String.valueOf(dataSet.get(listPosition).getRating())));
productCost.setText("RM " + dataSet.get(listPosition).getPrice());
productDiscount.setText(dataSet.get(listPosition).getDiscount());
if (dataSet.get(listPosition).getSpecial().trim().length() != 0) {
myViewHolder.special.setText("RM " + dataSet.get(listPosition).getSpecial());
strikeThroughText(productCost);
}
break;
case LOADING:
LoadingVH loadingVH = (LoadingVH) holder;
if (retryPageLoad) {
loadingVH.mErrorLayout.setVisibility(View.VISIBLE);
loadingVH.mProgressBar.setVisibility(View.GONE);
loadingVH.mErrorTxt.setText(
errorMsg != null ?
errorMsg :
context.getString(R.string.error_msg_unknown));
} else {
loadingVH.mErrorLayout.setVisibility(View.GONE);
loadingVH.mProgressBar.setVisibility(View.VISIBLE);
}
break;
}
}
private void strikeThroughText(TextView price) {
price.setPaintFlags(price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
#Override
public int getItemCount() {
return dataSet == null ? 0 : dataSet.size();
//return dataSet.size();
}
#Override
public int getItemViewType(int position) {
return (position == dataSet.size() - 1 && isLoadingAdded) ? LOADING : ITEM;
}
public com.example.it.camanagement.model.CategoryProduct getItem(int position) {
return dataSet.get(position);
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView productName, productColor, productCost, productDistCount, product_id, productModel, productQuantity, special;
RatingBar productRasting;
ImageView productImage;
public MyViewHolder(View itemView) {
super(itemView);
this.productName = (TextView) itemView.findViewById(R.id.product_name);
this.productColor = (TextView) itemView.findViewById(R.id.product_color);
this.productCost = (TextView) itemView.findViewById(R.id.cost);
this.productDistCount = (TextView) itemView.findViewById(R.id.discount);
this.productRasting = (RatingBar) itemView.findViewById(R.id.product_rating);
this.product_id = (TextView) itemView.findViewById(R.id.product_iid);
this.productQuantity = (TextView) itemView.findViewById(R.id.quantity);
this.productModel = (TextView) itemView.findViewById(R.id.modelProduct);
//this.textViewVersion = (TextView) itemView.findViewById(R.id.textViewVersion);
this.productImage = (ImageView) itemView.findViewById(R.id.product_image);
this.special = (TextView) itemView.findViewById(R.id.special);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent i = new Intent(context, ProductDescription.class);
i.putExtra("productName", ((TextView) v.findViewById(R.id.product_name)).getText().toString());
i.putExtra("product_id", ((TextView) v.findViewById(R.id.product_iid)).getText().toString());
context.startActivity(i);
if (getPosition() == 0) {
// Toast.makeText(v.getContext(), " On CLick one", Toast.LENGTH_SHORT).show();
}
if (getPosition() == 1) {
//Toast.makeText(v.getContext(), " On CLick Two", Toast.LENGTH_SHORT).show();
}
if (getPosition() == 2) {
// Toast.makeText(v.getContext(), " On CLick Three", Toast.LENGTH_SHORT).show();
}
if (getPosition() == 3) {//
// Toast.makeText(v.getContext(), " On CLick Fore", Toast.LENGTH_SHORT).show();
}
}
});
}
}
protected class LoadingVH extends RecyclerView.ViewHolder {
private ProgressBar mProgressBar;
private ImageButton mRetryBtn;
private TextView mErrorTxt;
private LinearLayout mErrorLayout;
public LoadingVH(View itemView) {
super(itemView);
mProgressBar = (ProgressBar) itemView.findViewById(R.id.loadmore_progress);
mRetryBtn = (ImageButton) itemView.findViewById(R.id.loadmore_retry);
mErrorTxt = (TextView) itemView.findViewById(R.id.loadmore_errortxt);
mErrorLayout = (LinearLayout) itemView.findViewById(R.id.loadmore_errorlayout);
}
}
}
//Recycler View
categoryProduct = (RecyclerView) findViewById(R.id.categoryProductList);
categoryProductAdapter = new CategoryProduct(categoryProduct,categoryProductList, context);
categoryProduct.setAdapter(categoryProductAdapter);
categoryProduct.setNestedScrollingEnabled(false);
categoryProduct.setHasFixedSize(false);
girdLayoutManager = new GridLayoutManager(CategoryDetails.this, 2);
categoryProduct.setLayoutManager(girdLayoutManager);
//scroll Listener
scrollListener = new EndlessRecyclerViewScrollListener(girdLayoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to the bottom of the list
Log.d("pageCount", "" + page);
Log.d("FirstVisibleITEM", "" + girdLayoutManager.findFirstVisibleItemPosition());
Log.d("LastVisibleITEM", "" + girdLayoutManager.findLastVisibleItemPosition());
}
};
categoryProduct.addOnScrollListener(scrollListener);
Finally solved it, Issue was: I was creating the object of layout manager two times. one in method(API response received and after notify the adapter) and another one in OnCreate() method of activity. after removing one object from method( API response received and after notify the adapter), fixed the issue.
Related
"Memory" rose quickly after open the Fragment that contains RecyclerView.When scorll up and down several times,"memory" continue to rise,and then show OOM and Force Close.
The following is the RecyclerView screenshot:
The following is my Adapter code:
I just use one RecyclerView the full page and nested a GridView at the first item;
public class CategoryPagerItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
//热门分类
public static final int VIEW_TYPE_HOT_SUB_CATE = 1;
//banner+商品横滑推荐
public static final int VIEW_TYPE_PROMOTION_LIST = 2;
public static final int VIEW_TYPE_PROMOTION_LIST_LABEL = 3;
//商品集合
public static final int VIEW_TYPE_GOODS_LIST = 4;
//商品集合标签
public static final int VIEW_TYPE_GOODS_LIST_LABEL = 5;
//加载更多
public static final int VIEW_TYPE_GOODS_LIST_MORE = 6;
public static final int COUNT_HOT_SUB_CATE=1;
public static final int COUNT_HOT_GOODS_LIST_LABEL=1;
public static final int COUNT_HOT_GOODS_LIST_MORE=1;
private String mTagId;//TabLayout的title对应的tagid
private String mTitleName;//TabLayout的title对应的name
private int mIndex = -1;//ViewPager的index
private int mLevel = 1;//级别分类
private Context mContext;
//相关的banner+横滑商品
private ArrayList<CategoryList.RelatedTagListEntity> mRelatedTagListEntityList;
//热门分类
private ArrayList<CategoryList.HotSubCategoryListEntity> mHotSubCategoryListEntityList;
//商品列表
private ArrayList<CategoryList.GoodListEntity> mGoodListEntityList;
private int mRelatedTagSize, mGoodsListSize;
private OnGoodsItemClickListener mOnGoodsItemClickListener;
public CategoryPagerItemAdapter(Context context, String tagId, String titleName, int index) {
mTagId = tagId;
mTitleName = titleName;
mIndex = index;
mContext = context;
}
public void resetData(ArrayList<CategoryList.HotSubCategoryListEntity> hotSubCategoryListEntityList,
ArrayList<CategoryList.RelatedTagListEntity> relatedTagListEntityList,
ArrayList<CategoryList.GoodListEntity> goodListEntityList, int level) {
mHotSubCategoryListEntityList = hotSubCategoryListEntityList;
mRelatedTagListEntityList = relatedTagListEntityList;
mGoodListEntityList = goodListEntityList;
mRelatedTagSize = mRelatedTagListEntityList == null ? 0 : mRelatedTagListEntityList.size();
mGoodsListSize = mGoodListEntityList == null ? 0 : mGoodListEntityList.size();
mLevel = level;
notifyDataSetChanged();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
//头部的十个分类
if (viewType == VIEW_TYPE_HOT_SUB_CATE) {
return new HotSubCateViewHolder(layoutInflater.inflate(R.layout.category_classify_item_hot_sub_cate, parent, false));
} else if (viewType == VIEW_TYPE_PROMOTION_LIST) {//banner+商品横滑推荐
return new PromotionViewHolder(layoutInflater.inflate(R.layout.category_classify_item_related, parent, false));
} else if (viewType == VIEW_TYPE_GOODS_LIST) {//商品列表
return new GoodListViewHolder(layoutInflater.inflate(R.layout.category_classify_item_goods_list, parent, false));
} else if (viewType == VIEW_TYPE_GOODS_LIST_LABEL) {
return new GoodListLabelViewHolder(layoutInflater.inflate(R.layout.category_classify_item_goods_list_label, parent, false));
} else if (viewType == VIEW_TYPE_GOODS_LIST_MORE) {//更多
return new MoreGoodsListViewHolder(layoutInflater.inflate(R.layout.category_classify_item_more, parent, false));
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder vh, final int position) {
switch (vh.getItemViewType()) {
//热门分类
case VIEW_TYPE_HOT_SUB_CATE:
final HotSubCateViewHolder hotSubCateHolder = (HotSubCateViewHolder) vh;
int horizontalSpacing = (UJiPin.SCREEN_WIDTH - UDensity.dip2px(mContext, 16) * 2 - UDensity.dip2px(mContext, 50) * 5) / 4;
hotSubCateHolder.mGridview.setHorizontalSpacing(horizontalSpacing);
hotSubCateHolder.mGridview.setVerticalSpacing(UDensity.dip2px(mContext, 20));
final CategoryHotSubCateAdapter categoryHotSubCateAdapter = new CategoryHotSubCateAdapter(mContext, mHotSubCategoryListEntityList);
hotSubCateHolder.mGridview.setAdapter(categoryHotSubCateAdapter);
hotSubCateHolder.mGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
int hotSubViewType = categoryHotSubCateAdapter.getItemViewType(pos);
CategoryList.HotSubCategoryListEntity hotSubCategoryListEntity = mHotSubCategoryListEntityList.get(pos);
if (hotSubViewType == CategoryHotSubCateAdapter.VIEW_TYPE_HOT_SUB_CATE) {//热门分类
JumpUtils.JumpClassifyList((BaseActivity) mContext, hotSubCategoryListEntity.getLevel(), hotSubCategoryListEntity.getTag_id(), hotSubCategoryListEntity.getName());
UJPTrack.getInstance().setTrack((BaseActivity) mContext, UJPTrack.PAGE_CLASS_ + UString.urlEncode(hotSubCategoryListEntity.getName()),
"class-1-" + UString.urlEncode(hotSubCategoryListEntity.getName()));
} else if (hotSubViewType == CategoryHotSubCateAdapter.VIEW_TYPE_HOT_SUB_CATE_MORE) {//点击more
Intent intent = new Intent(mContext, CategoryPagerMoreActivity.class);
intent.putExtra(CategoryPagerMoreActivity.EXTRA_STRING_CATEGORY_NAME, mTitleName);
intent.putExtra(CategoryPagerMoreActivity.EXTRA_INT_CATEGORY_INDEX, mIndex);
intent.putExtra(CategoryPagerMoreActivity.EXTRA_STRING_CATEGORY_TAG_ID, mTagId);
mContext.startActivity(intent);
UJPTrack.getInstance().setTrack((BaseActivity) mContext,
UJPTrack.PAGE_CLASS_ + UString.urlEncode(mTitleName),
"class-1-more");
}
}
});
break;
case VIEW_TYPE_PROMOTION_LIST://banner+横滑
PromotionViewHolder promotionViewHolder = (PromotionViewHolder) vh;
final int promotionPosition = position - COUNT_HOT_SUB_CATE;
//防止recyclerview复用出现错乱的办法是有if必须有else,并且处理相反
GridLayoutManager.LayoutParams promotionLP = (GridLayoutManager.LayoutParams) promotionViewHolder.mContainer.getLayoutParams();
if (promotionPosition == 0) {//如果是第一个,则显示“相关推荐“
promotionViewHolder.mLabel.setVisibility(View.VISIBLE);
promotionLP.setMargins(-UDensity.dip2px(mContext, 5), UDensity.dip2px(mContext, 16), -UDensity.dip2px(mContext, 5), 0);
} else {
promotionViewHolder.mLabel.setVisibility(View.GONE);
promotionLP.setMargins(-UDensity.dip2px(mContext, 5), UDensity.dip2px(mContext, 4), -UDensity.dip2px(mContext, 5), 0);
}
promotionViewHolder.mContainer.setLayoutParams(promotionLP);
final CategoryList.RelatedTagListEntity relatedTagListEntity = mRelatedTagListEntityList.get(promotionPosition);
FrescoImageLoader.getInstance().load(promotionViewHolder.mCover, relatedTagListEntity.getCover());
//点击banner
promotionViewHolder.mCover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JumpUtils.JumpActivityTopic((BaseActivity) mContext, relatedTagListEntity.getName(),
relatedTagListEntity.getTag_id(), null, promotionPosition);
UJPTrack.getInstance().setTrack((BaseActivity) mContext, UJPTrack.PAGE_LABEL_ + UString.urlEncode(relatedTagListEntity.getName()),
"class-2-" + covertInt(promotionPosition + 1));
}
});
final CategoryChoiceTagAdapter adapter = new CategoryChoiceTagAdapter(mContext);
//点击横滑商品
adapter.setOnItemClickListener(new CategoryChoiceTagAdapter.OnItemClickListener() {
#Override
public void onTag4ItemClick(final CategoryList.GoodListEntity goodListEntity, int position, View view) {
Jumper.newJumper().putString(GoodsDetailActivity.EXTRA_STRING_GOODID, goodListEntity.getGoods_id() + "")
.putString(GoodsDetailActivity.EXTRA_STRING_SOURCENAME, "分类")
.putString(GoodsDetailActivity.EXTRA_STRING_SOURCEID, "活动横滑")
.jump((BaseActivity) mContext, GoodsDetailActivity.class);
UJPTrack.getInstance().setTrack((BaseActivity) mContext, UJPTrack.PAGE_GOOD + goodListEntity.getGoods_id(),
"class-2-" + covertInt(promotionPosition + 1));
}
});
promotionViewHolder.mSlideMoreRecycleView.setAdapter(adapter);
adapter.setDataRefresh(relatedTagListEntity.getGoods_list());
//横滑
promotionViewHolder.mSlideMoreRecycleView.setOnSlideTwiceLisner(new SlideMoreRecycleView.SlideTwiceLisner() {
#Override
public void onSliding(RecyclerView recyclerView) {
JumpUtils.JumpActivityTopic((BaseActivity) mContext, relatedTagListEntity.getName(),
relatedTagListEntity.getTag_id(), "", promotionPosition);
}
});
break;
case VIEW_TYPE_GOODS_LIST_LABEL://商品列表的label
break;
case VIEW_TYPE_GOODS_LIST://商品列表
int goodsListPosition = position - COUNT_HOT_SUB_CATE - mRelatedTagSize - COUNT_HOT_GOODS_LIST_LABEL;
final CategoryList.GoodListEntity goodListEntity = mGoodListEntityList.get(goodsListPosition);
final GoodListViewHolder goodsListHolder = (GoodListViewHolder) vh;
ViewCompat.setTransitionName(goodsListHolder.ivCover, mContext.getString(R.string.transition_name) + position);
goodsListHolder.rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mOnGoodsItemClickListener != null) {
mOnGoodsItemClickListener.onItemClick(goodsListHolder.rootView, goodListEntity, position, goodListEntity.getThumbnail());
}
}
});
goodsListHolder.tv_goods_selling_point.setText(goodListEntity.getSelling_point());
if (!TextUtils.isEmpty(goodListEntity.getThumbnail()))
FrescoImageLoader.getInstance().load(goodsListHolder.ivCover, goodListEntity.getThumbnail());
if (!TextUtils.isEmpty(goodListEntity.getMark())) {
goodsListHolder.ivGroupLogo.setVisibility(View.VISIBLE);
FrescoImageLoader.getInstance().load(goodsListHolder.ivGroupLogo, goodListEntity.getMark());
} else {
goodsListHolder.ivGroupLogo.setVisibility(View.GONE);
}
goodsListHolder.tvDescription.setText(goodListEntity.getGoods_name());
if (!TextUtils.isEmpty(goodListEntity.getGoods_price()))
goodsListHolder.tvPrice.setText(String.format(mContext.getString(R.string.rmb), goodListEntity.getGoods_price()));
//售罄
if (goodListEntity.getProduct_stock_total() <= 0)
goodsListHolder.ivSoldOut.setVisibility(View.VISIBLE);
else
goodsListHolder.ivSoldOut.setVisibility(View.GONE);
break;
case VIEW_TYPE_GOODS_LIST_MORE://更多推荐
MoreGoodsListViewHolder moreGoodsListViewHolder = (MoreGoodsListViewHolder) vh;
moreGoodsListViewHolder.mContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JumpUtils.JumpClassifyList((BaseActivity) mContext, mLevel, mTagId, mTitleName);
UJPTrack.getInstance().setTrack((BaseActivity) mContext, UJPTrack.PAGE_CLASS_ + UString.urlEncode(mTitleName), UJPTrack.PAGE_CLASS_CLASS + UString.urlEncode(mTitleName));
}
});
break;
}
}
#Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
}
#Override
public int getItemViewType(int position) {
if (position == 0) {
return VIEW_TYPE_HOT_SUB_CATE;
} else if (position < COUNT_HOT_SUB_CATE + mRelatedTagSize) {
return VIEW_TYPE_PROMOTION_LIST;
} else if (position < COUNT_HOT_SUB_CATE + mRelatedTagSize + COUNT_HOT_GOODS_LIST_LABEL) {
return VIEW_TYPE_GOODS_LIST_LABEL;
} else if (position < COUNT_HOT_SUB_CATE + mRelatedTagSize + COUNT_HOT_GOODS_LIST_LABEL + mGoodsListSize) {
return VIEW_TYPE_GOODS_LIST;
} else {
return VIEW_TYPE_GOODS_LIST_MORE;
}
}
#Override
public int getItemCount() {
return mGoodsListSize + mRelatedTagSize + COUNT_HOT_SUB_CATE +
COUNT_HOT_GOODS_LIST_LABEL + COUNT_HOT_GOODS_LIST_MORE;
}
//头部的热门分类
private static class HotSubCateViewHolder extends RecyclerView.ViewHolder {
private MyGridview mGridview;
HotSubCateViewHolder(View view) {
super(view);
mGridview = (MyGridview) view.findViewById(R.id.grid_view);
}
}
//banner+推荐横滑
private static class PromotionViewHolder extends RecyclerView.ViewHolder {
private SimpleDraweeView mCover;
private LinearLayout mContainer;
private TextView mLabel;
private SlideMoreRecycleView mSlideMoreRecycleView;
PromotionViewHolder(View view) {
super(view);
mContainer = (LinearLayout) view.findViewById(R.id.ll);
mLabel = (TextView) view.findViewById(R.id.label);
mCover = (SimpleDraweeView) view.findViewById(R.id.iv_cover);
mSlideMoreRecycleView = (SlideMoreRecycleView) view.findViewById(rv_tag_list);
}
}
//商品列表
private static class GoodListViewHolder extends RecyclerView.ViewHolder {
View rootView;
SimpleDraweeView ivCover;
TextView tvDescription;
TextView tvPrice;
TextView tv_goods_selling_point;
ImageView ivSoldOut;
SimpleDraweeView ivGroupLogo;
GoodListViewHolder(View v) {
super(v);
rootView = v;
ivCover = (SimpleDraweeView) v.findViewById(R.id.iv_cover);
tvDescription = (TextView) v.findViewById(R.id.tv_descrption);
tvPrice = (TextView) v.findViewById(R.id.tv_price);
tv_goods_selling_point = (TextView) v.findViewById(R.id.tv_goods_selling_point);
ivSoldOut = (ImageView) v.findViewById(R.id.iv_sold_out);
ivGroupLogo = (SimpleDraweeView) v.findViewById(R.id.iv_group_tag);
}
}
private static class GoodListLabelViewHolder extends RecyclerView.ViewHolder {
TextView mLabel;
public GoodListLabelViewHolder(View itemView) {
super(itemView);
mLabel = (TextView) itemView.findViewById(R.id.label);
}
}
private static class MoreGoodsListViewHolder extends RecyclerView.ViewHolder {
private LinearLayout mContainer;
MoreGoodsListViewHolder(View itemView) {
super(itemView);
mContainer = (LinearLayout) itemView.findViewById(R.id.container);
}
}
//点击双栏列表接口
public interface OnGoodsItemClickListener {
void onItemClick(View rootView, CategoryList.GoodListEntity goodListEntity, int position, String imageUrl);
}
public void addOnGoodsItemClickListener(OnGoodsItemClickListener listener) {
mOnGoodsItemClickListener = listener;
}
public String covertInt(int value) {
return value <= 9 ? ("0" + value) : value + "";
}
I have it clicked and it gets up to it and shows the right getText() method but the setText method is not working...
userAdapter.setOnEntryClickListener(new UserAdapter.OnEntryClickListener() {
#Override
public void onEntryClick(View view, int position) {
DatabaseUser user = dbUsersList.get(position);
TextView clickedView = (TextView) view.findViewById(R.id.userAdapterFollowBtn);
if(view == clickedView) {
if (clickedView.getText().equals("following")) {
Log.d(Constants.DEBUG, " THE CLICK VIEW IS " + clickedView.getText());
//APPLY Following
String txtFollow = "follow";
clickedView.setText(txtFollow);
if (user.getIsChanged() == 0) {
user.setIsChanged(1);
} else {
user.setIsChanged(0);
}
user.setIsType(3);
db.updateFollow(user);
userAdapter.notifyDataSetChanged();
} else {
clickedView.setText("following");
if (user.getIsChanged() == 0) {
user.setIsChanged(1);
} else {
user.setIsChanged(0);
}
user.setIsType(0);
db.updateFollow(user);
userAdapter.notifyDataSetChanged();
}
} else {
Toast.makeText(getApplicationContext(), user.getUsername() + " is selected!", Toast.LENGTH_SHORT).show();
takeToUserProfile(dbUsersList.get(position));
}
}
});
Here is the adapter class:
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.MyViewHolder> {
private List<DatabaseUser> dbUsersList, followingList;
private DatabaseHelper db;
private Context context;
private Typeface typeFace, italicTypeface, boldTypeface;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView userAdapterUsername, userAdapterFollowBtn;
public ImageView userAdapterUserPicture;
public MyViewHolder(View view) {
super(view);
userAdapterUsername = (TextView) view.findViewById(R.id.userAdapterUsername);
userAdapterFollowBtn = (TextView) view.findViewById(R.id.userAdapterFollowBtn);
userAdapterUserPicture = (ImageView) view.findViewById(R.id.userAdapterUserPicture);
Log.d(Constants.DEBUG, "IN MY VIEW HOLDER");
view.setOnClickListener(this);
userAdapterFollowBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mOnEntryClickListener != null) {
Log.d(Constants.DEBUG, "IN On click");
mOnEntryClickListener.onEntryClick(v, getAdapterPosition());
}
}
}
private static OnEntryClickListener mOnEntryClickListener;
public interface OnEntryClickListener {
void onEntryClick(View view, int position);
}
public void setOnEntryClickListener(OnEntryClickListener onEntryClickListener) {
mOnEntryClickListener = onEntryClickListener;
}
public UserAdapter(Context mContext, List<DatabaseUser> usersList, List<DatabaseUser> passedFollowing, Typeface myTypeface, Typeface myTypefaceItalic, Typeface myTypefaceBold) {
context = mContext;
dbUsersList = usersList;
followingList = passedFollowing;
typeFace = myTypeface;
italicTypeface = myTypefaceItalic;
boldTypeface = myTypefaceBold;
Log.d(Constants.DEBUG, "IN MY User ADAPTER CONSTRUCTOR");
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.follow_item, parent, false);
Log.d(Constants.DEBUG, "RETURN ITEM VIEW HOLDER");
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
DatabaseUser user = dbUsersList.get(position);
holder.userAdapterUsername.setTypeface(boldTypeface);
holder.userAdapterUsername.setText(user.getUsername());
final int pos = getItemViewType(position);
//TODO Create pic link
if(containsId(dbUsersList.get(pos), followingList)) {
//Then show following
holder.userAdapterFollowBtn.setText("following");
} else {
//show follow
holder.userAdapterFollowBtn.setText("follow");
}
String userspic = dbUsersList.get(pos).getPicture();
if(userspic == null) {
//SET DEFAULT OR PUT DEFAULT IN XML AND DO NOTHING IT SHOULD SHOW DEFAULT PIC
} else {
//TODO setupUser Pic
String img1 = "http://www.hindustantimes.com/Images/popup/2015/6/kungfu2.jpg";
Picasso.with(context).load(img1).transform(new RoundedTransformation()).into(holder.userAdapterUserPicture);
}
}
#Override
public int getItemCount() {
return dbUsersList.size();
}
public static boolean containsId(DatabaseUser currentUser, List<DatabaseUser> list) {
for (DatabaseUser object : list) {
if (currentUser.getUserId().equals(object.getUserId())) {
return true;
}
}
return false;
}
#Override
public int getItemViewType(int position) {
return position;
}
}
your dbUsersList is not updating. please check your user object in dbUsersList after notify data set change.
What ended up being the problem is that I had passed in the followingList, so I never re-called to grab the new following from the db on update. The update was happening I just had to re-grab the followingList from the db to have an updated list to check against like so in a new method that was passing the list back to the contains method.
db.grabFollowersList();
I am using a cardview with recyclerview with hardcoded values such as string arrays. But now i want to add new cardview on each button click with user enter values and user select image and keep remain all cardviews on app exit.I mean to say that cardview should be added one by one only.Any solution plz guide me.
cardview Adapter class
public class CardViewDataAdapter extends RecyclerView.Adapter<CardViewDataAdapter.ViewHolder> {
private static ArrayList<FeddProperties> dataSet;
private static Context context;
public CardViewDataAdapter(Context context, ArrayList<FeddProperties> os_versions) {
this.context = context;
dataSet = os_versions;
}
#Override
public CardViewDataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.card_view, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(CardViewDataAdapter.ViewHolder viewHolder, int i) {
FeddProperties fp = dataSet.get(i);
viewHolder.vehicleNumber.setText(fp.getTitle());
viewHolder.iconView.setImageResource(fp.getThumbnail());
viewHolder.feed = fp;
}
#Override
public int getItemCount() {
return dataSet.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView vehicleNumber;
public ImageView iconView;
public FeddProperties feed;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
vehicleNumber = (TextView) itemLayoutView
.findViewById(R.id.vehiclenumber);
iconView = (ImageView) itemLayoutView
.findViewById(R.id.iconId);
itemLayoutView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), InformingUser.class);
v.getContext().startActivity(intent);
((MainActivity) context).getSupportFragmentManager().beginTransaction().replace
(R.id.containerView, new InformingUser()).commit();
//Toast.makeText(v.getContext(), "os version is: " + feed.getTitle(), Toast.LENGTH_SHORT).show();
}
});
}
}
Java file....
private void initContrls()
{
SharedPreferences prefs = context.getSharedPreferences(MY_PREFS_NAME, 0);
vehiclecatory = prefs.getString("vehicle_category", "");
vehicletype = prefs.getString("vehicle_type", "");
String versions = prefs.getString("city", "")+" "+prefs.getString("dis", "")+" "+prefs.getString("number", "");
String vehicleCompany = prefs.getString("company", "")+" "+prefs.getString("model", "");
if(vehiclecatory.equals("1"))
{
if (vehicletype.equals("1"))
{
icons = R.drawable.contwowheel;
}
else if (vehicletype.equals("2"))
{
icons = R.drawable.comfourwheel;
}
else if (vehicletype.equals("3"))
{
icons = R.drawable.comheavy;
}
}
else if (vehiclecatory.equals("2"))
{
if (vehicletype.equals("1"))
{
icons = R.drawable.nontwowheel;
}
else if (vehicletype.equals("2"))
{
icons = R.drawable.nonfourwheel;
}
else if (vehicletype.equals("3"))
{
icons = R.drawable.nonheavy;
}
}
os_versions = new ArrayList<FeddProperties>();
for (int i = 0; i < 2; i++) {
FeddProperties feed = new FeddProperties();
feed.setTitle(versions);
feed.setVehicleCompany(vehicleCompany);
feed.setThumbnail(icons);
os_versions.add(feed);
}
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
mAdapter = new CardViewDataAdapter(context,os_versions);
recyclerView.setAdapter(mAdapter);
}
here there is an example to add cardview dinamically
In this example cardview are create with for:
for (int index = 0; index < 20; index++) {
DataObject obj = new DataObject("Some Primary Text " + index,
"Secondary " + index);
results.add(index, obj);
}
but you can inser into onClick action :)
I have a problem that I have been trying to solve for too long but I can't know what causes the problem.
I have a marks list that contains Test objects and subject strings that I use as sections between marks, I use getClass() method to determine if an object is a string or Test, if it is a string, I hide the test's RelativeLayout, if it is a test then I hide the RelativeLayout of the subject. But when scrolling, items get removed and and re-added randomly.
my adapter's class:
public class MarksAdapter extends RecyclerView.Adapter<MarksAdapter.MyHolder>{
public class MyHolder extends RecyclerView.ViewHolder{
RelativeLayout card;
TextView title;
TextView total;
View divider;
int posito;
RelativeLayout group;
TextView groupTitle;
TextView groupMark;
public MyHolder(View itemView) {
super(itemView);
this.card = (RelativeLayout)itemView.findViewById(R.id.card);
this.title = (TextView)itemView.findViewById(R.id.title);
this.total = (TextView)itemView.findViewById(R.id.mark);
this.divider = itemView.findViewById(R.id.item_divider);
this.group = (RelativeLayout)itemView.findViewById(R.id.group);
this.groupTitle = (TextView)itemView.findViewById(R.id.group_title);
this.groupMark = (TextView)itemView.findViewById(R.id.group_mark);
}
}
final ArrayList marks;
Context ctx;
String selectedSem;
TestDatabase db;
public MarksAdapter(Context c, ArrayList marks,String sem,TestDatabase db,ArrayList<Integer> sections){
this.marks = marks;
ctx = c;
selectedSem = sem;
this.db = db;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyHolder(LayoutInflater.from(ctx).inflate(R.layout.mark_child, parent, false));
}
int lastPosition = -1;
int offset = 0;
#Override
public void onBindViewHolder(final MyHolder holder, final int positioner) {
holder.posito = positioner;
if(marks.get(holder.posito).getClass() == Test.class) {
holder.group.setVisibility(View.GONE);
//mark
final Test test = (Test)marks.get(positioner);
holder.title.setText(test.getName());
holder.total.setText(String.format(ctx.getString(R.string.new_m_sum), test.getMarkGot(), test.getMarkOver()));
//add here
holder.card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ctx,addTest.class);
Test mark = (Test)marks.get(holder.posito);
i.putExtra("t_name",mark.getName());
i.putExtra("subject",mark.getSubject());
i.putExtra("mark_got",mark.getMarkGot());
i.putExtra("mark_over",mark.getMarkOver());
i.putExtra("mode","edit");
i.putExtra("oldId", mark.getId());
ctx.startActivity(i);
}
});
holder.card.setLongClickable(true);
holder.card.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
final Dialog dialo = new Dialog(ctx);
dialo.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialo.setContentView(R.layout.material_dialog);
TextView title = (TextView) dialo.findViewById(R.id.title);
TextView body = (TextView) dialo.findViewById(R.id.body);
Button negative = (Button) dialo.findViewById(R.id.negative);
negative.setText(ctx.getString(R.string.cancel));
Button positive = (Button) dialo.findViewById(R.id.positive);
positive.setText(ctx.getString(R.string.Delete));
title.setText(ctx.getString(R.string.d));
body.setText(ctx.getString(R.string.q_delete) + " " + test.getName() + " " + ctx.getString(R.string.de_comp));
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialo.dismiss();
}
});
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vir) {
TestDatabase tb = new TestDatabase(ctx);
SemesterDatabase semesterDatabase = new SemesterDatabase(ctx);
tb.deleteTest(holder.posito, semesterDatabase.getSelected().getName());
MarksAdapter.this.notifyItemRemoved(holder.posito);
marks.remove(holder.posito);
for (int i = 0; i < marks.size(); i++) {
if(!(marks.get(i) instanceof Test)) {
String sub = String.valueOf(marks.get(i));
if(db.isNoValue(sub,selectedSem)){
marks.remove(i);
notifyItemRemoved(i);
}
}
}
dialo.dismiss();
}
});
dialo.show();
return true;
}
});
}else {
holder.group.setVisibility(View.VISIBLE);
holder.card.setVisibility(View.GONE);
//group
if(holder.posito == 0) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)holder.group.getLayoutParams();
params.setMargins(0,0,0,0);
holder.group.setLayoutParams(params);
}
String sub = String.valueOf(marks.get(holder.posito));
holder.groupTitle.setText(sub);
holder.groupMark.setText(db.getTotalSubjectMarks(sub,selectedSem));
}
if(lastPosition < holder.posito) {
if(holder.card.getVisibility() == View.VISIBLE) {
Animation slide = AnimationUtils.loadAnimation(ctx, R.anim.marks);
slide.setInterpolator(new AccelerateInterpolator());
slide.setDuration(700);
offset += 100;
slide.setStartOffset(offset);
holder.card.startAnimation(slide);
} else {
Animation slide = AnimationUtils.loadAnimation(ctx, R.anim.mark_groups);
slide.setInterpolator(new AccelerateInterpolator());
slide.setDuration(700);
offset += 50;
slide.setStartOffset(offset);
holder.group.startAnimation(slide);
}
lastPosition = holder.posito;
}
}
#Override
public int getItemCount() {
return marks.size();
}
}
Note: I already tried the itemViewType method but it didn't work for me
Thanks in advance!
I believe you missed to set holder.card back to visible, like this
if(marks.get(holder.posito).getClass() == Test.class) {
holder.card.setVisibility(View.Visible); //add back this
holder.group.setVisibility(View.GONE);
Here is my code. I have cardviews and in some i have one pic and in some there is no pic. But after scroll up and down i get pictures in every CardView (pics from previous cardview) event if there should not be any pic at all (***.size()=0). I think the problem is here
if (mDataset.get(position).getAdv_pics().size()>0){
String pic = mDataset.get(position).getAdv_pics().get(0);
ImageView image = new ImageView(mActivity);
Log.d("!!!!", position + " http://m2.biz.ua" + holder.pic + "_small.jpg");
holder.mLayout.addView(image, 1);
Picasso.with(mActivity)
.load("http://m2.biz.ua" + pic + "_small.jpg")
.resize(100, 100)
.centerCrop()
.into(image);
}
FlatListCardAdapter.class
public class FlatListCardAdapter extends RecyclerView.Adapter<FlatListCardAdapter.ViewHolder> {
private List<Flat> mDataset;
private Activity mActivity;
private String[] currency;
private OnCardClickListener mListener;
public interface OnCardClickListener{
void getFlat(Flat flatId);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mAdvText, mAdvRooms, mAdvPrice, mAdvAddr;
public LinearLayout mLayout;
public ImageButton mCallButton;
public Button test;
public String pic;
public ImageView smallImage;
public View view;
private CardView mCardView;
public ViewHolder(View v ) {
super(v);
view=v;
mAdvText = (TextView) v.findViewById(R.id.advText);
mAdvRooms = (TextView) v.findViewById(R.id.advRooms);
mAdvPrice = (TextView) v.findViewById(R.id.advPrice);
mAdvAddr = (TextView) v.findViewById(R.id.advAddr);
mLayout = (LinearLayout) v.findViewById(R.id.picMainLayout);
mCallButton = (ImageButton) v.findViewById(R.id.callAdv);
mCardView = (CardView) v.findViewById(R.id.card_view);
}
}
public FlatListCardAdapter(Activity activity, List<Flat> dataset, OnCardClickListener mListener) {
mDataset = dataset;
mActivity = activity;
this.mListener = mListener;
}
#Override
public FlatListCardAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_realty_list_card_custom, parent, false);
ViewHolder vh = new ViewHolder(v);
currency=mActivity.getResources().getStringArray(R.array.currency);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Flat mFlat = mDataset.get(position);
String mCurrency="";
if ( Integer.parseInt(mFlat.getAdv_currency())>0 ){
mCurrency=currency[Integer.parseInt(mFlat.getAdv_currency())];
}
holder.mAdvRooms.setText(mFlat.getAdv_rooms()+" ");
holder.mAdvPrice.setText(mFlat.getAdv_price()+" "+mCurrency);
holder.mAdvText.setText(mFlat.getAdv_text());
holder.mAdvAddr.setText(mFlat.getAdv_addr());
holder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("!!!!", mFlat.getId());
try {
mListener = (MainActivity) mActivity;
mListener.getFlat(mFlat);
} catch (ClassCastException e) {
throw new ClassCastException(mActivity.toString() + " must implement OnArticleSelectedListener");
}
}
});
holder.mCallButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
List<String> phone = mFlat.getAdv_phone();
if (phone.size()>0) {
Toast.makeText(mActivity, phone.get(0), Toast.LENGTH_SHORT).show();
}
}
});
Log.d("!!!!", "SIZE: " +mDataset.get(position).getAdv_pics().size());
if (mDataset.get(position).getAdv_pics().size()>0){
String pic = mDataset.get(position).getAdv_pics().get(0);
ImageView image = new ImageView(mActivity);
Log.d("!!!!", position + " http://****" + holder.pic + "_small.jpg");
holder.mLayout.addView(image, 1);
Picasso.with(mActivity)
.load("http://****" + pic + "_small.jpg")
.resize(100, 100)
.centerCrop()
.into(image);
}
/**/
}
#Override
public int getItemCount() {
if (mDataset==null){
return 0;
}
return mDataset.size();
}
}
Item view is reused in the RecyclerView. The issue is here
if (mDataset.get(position).getAdv_pics().size()>0){
...
}
add else clause and set image as null there. As is shown in the code below
if (mDataset.get(position).getAdv_pics().size()>0){
...
}else{
image.setImageBitmap(null);
}