"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 + "";
}
Related
Want to add margin to gridview in the following manner.
Left margin for 2,4, 2,9, 12,14,..
Right margin for 3,5, 8,10, 13,15,..
Here is my code snippet which I tried to set margin to 2x2 items in grid view...
i.e positions - ..,2,3,4,5,..,7,8,9,10,..,12,13,14,15,..,17,18,19,20,.. like wise.
for 2,3,4,5 & 12,13,14,15,.. Getting the expected output. but my case failed for 7,8,9,10 & 17,18,19,20 series.
Help me to solve this. Confused to solve this mathematical puzzle.
Thanks in advance.
public class BoxFeedAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<BoxFeedResult> boxFeedResults;
private Context mContext;
private RecyclerViewItemClickListener viewItemClickListener;
private final int LARGE_TYPE = 0;
private final int SMALL_TYPE = 1;
private final int PROGRESS_TYPE = 2;
private int GRID_VIEW_MARGIN_LEFT = 0;
private int GRID_VIEW_MARGIN_RIGHT = 0;
private int GRID_VIEW_MARGIN_TOP = 0;
private int GRID_VIEW_MARGIN_BOTTOM = 0;
private int GRID_VIEW_ROW_MARGIN = 0;
public BoxFeedAdapter(Context context, RecyclerViewItemClickListener viewItemClickListener) {
this.mContext = context;
this.viewItemClickListener = viewItemClickListener;
boxFeedResults = new ArrayList<>();
GRID_VIEW_MARGIN_LEFT = context.getResources().getDimensionPixelOffset(R.dimen.empty_dimen);
GRID_VIEW_MARGIN_RIGHT = context.getResources().getDimensionPixelOffset(R.dimen.empty_dimen);
GRID_VIEW_MARGIN_TOP = context.getResources().getDimensionPixelOffset(R.dimen.channel_row_padding);
GRID_VIEW_MARGIN_BOTTOM = context.getResources().getDimensionPixelOffset(R.dimen.empty_dimen);
GRID_VIEW_ROW_MARGIN = context.getResources().getDimensionPixelOffset(R.dimen.channel_row_padding_left);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == SMALL_TYPE) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_box_feed_series_banner, null);
return new BoxFeedSeriesListViewHolder(layoutView);
} else if (viewType == LARGE_TYPE) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_box_feed_episode_banner, null);
return new BoxFeedEpisodeViewHolder(layoutView);
} else {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.progress_item, null);
return new ProgressViewHolder(layoutView);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof BoxFeedSeriesListViewHolder) {
StaggeredGridLayoutManager.LayoutParams layoutParams = new StaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setFullSpan(false);
if ((position - 1) % 2 == 0) {
layoutParams.setMargins(GRID_VIEW_ROW_MARGIN, GRID_VIEW_MARGIN_TOP, GRID_VIEW_MARGIN_RIGHT, GRID_VIEW_MARGIN_BOTTOM);
} else {
layoutParams.setMargins(GRID_VIEW_MARGIN_LEFT, GRID_VIEW_MARGIN_TOP, GRID_VIEW_ROW_MARGIN, GRID_VIEW_MARGIN_BOTTOM);
}
holder.itemView.setLayoutParams(layoutParams);
final BoxFeedResult singleFeed = boxFeedResults.get(position);
final BoxFeedSeriesListViewHolder viewHolder = (BoxFeedSeriesListViewHolder) holder;
Glide.with(mContext)
.load(singleFeed.getA4MediumUrl())
.placeholder(R.drawable.bg_black)
.into(viewHolder.seriesImage);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, singleFeed.getId(), Toast.LENGTH_SHORT).show();
viewItemClickListener.onItemClickListioner(singleFeed, viewHolder.seriesImage, position);
}
});
} else if (holder instanceof BoxFeedEpisodeViewHolder) {
StaggeredGridLayoutManager.LayoutParams layoutParams = new StaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setFullSpan(true);
holder.itemView.setLayoutParams(layoutParams);
final BoxFeedResult singleFeed = boxFeedResults.get(position);
final BoxFeedEpisodeViewHolder viewHolder = (BoxFeedEpisodeViewHolder) holder;
Glide.with(mContext)
.load(singleFeed.getAspectMediumUrl())
.placeholder(R.drawable.bg_black)
.into(viewHolder.episodeImage);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, singleFeed.getId(), Toast.LENGTH_SHORT).show();
}
});
} else {
StaggeredGridLayoutManager.LayoutParams layoutParams = new StaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setFullSpan(true);
holder.itemView.setLayoutParams(layoutParams);
}
}
#Override
public int getItemCount() {
return boxFeedResults.size();
}
#Override
public int getItemViewType(int position) {
switch (boxFeedResults.get(position).getTileType()) {
case “large":
return LARGE_TYPE;
case “small":
return SMALL_TYPE;
default:
return PROGRESS_TYPE;
}
}
public void addList(List<BoxFeedResult> feedResults) {
this.boxFeedResults = feedResults;
notifyDataSetChanged();
}
}
Expected output is
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.
My code is as shown below:
public class PopularItemsAdapter extends RecyclerView.Adapter<PopularItemsAdapter.MyViewHolder>
implements MyCartListener {
private Context mContext;
private List<FoodTruckItem> foodTruckItemList;
private boolean isClickable = false;
private OnItemClickListener listener;
private List<FoodtruckInfo> foodtruckInfoList = new ArrayList<>();
private List<FoodTruckItem> sessionItem = new ArrayList<>();
private boolean isConflictResolved = false;
public int position = -1;
#Override
public void itemUpdated(int quantity, String itemId) {
for (int i = 0; i < foodTruckItemList.size(); i++) {
if (itemId.equals(foodTruckItemList.get(i).getItemId())) {
foodTruckItemList.get(i).setItemQuantityOrdered(quantity);
// notifyDataSetChanged();
}
}
}
#Override
public void itemRemoved(String itemId) {
for (int j = 0; j < foodTruckItemList.size(); j++) {
if (itemId.equals(foodTruckItemList.get(j).getItemId())) {
foodTruckItemList.remove(j);
// notifyDataSetChanged();
}
}
}
public void addConflictItem(int position) {
isConflictResolved = true;
notifyItemChanged(position);
}
public interface OnItemClickListener {
void onItemClick(FoodTruckItem foodTruckItem, FoodtruckInfo foodtruckInfo);
void showSnackBar(int items, boolean added, int position);
void showRestaurentClosed();
void showWarningDialog(int position);
}
public void addFoodInfo(List<FoodtruckInfo> foodtruckInfos) {
foodtruckInfoList.addAll(foodtruckInfos);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView itemName, foodPrice, addText, quantityText, addQuantity, removeQuantity;
public ImageView itemImage, itemTag;
public LinearLayout addLayout;
public MyViewHolder(View view) {
super(view);
itemTag = (ImageView) view.findViewById(R.id.itemTag);
itemImage = (ImageView) view.findViewById(R.id.itemImage);
itemName = (TextView) view.findViewById(R.id.itemName);
foodPrice = (TextView) view.findViewById(R.id.foodPrice);
addText = (TextView) view.findViewById(R.id.addText);
addLayout = (LinearLayout) view.findViewById(R.id.addLayout);
quantityText = (TextView) view.findViewById(R.id.quantityText);
addQuantity = (TextView) view.findViewById(R.id.addQuantity);
removeQuantity = (TextView) view.findViewById(R.id.removeQuantity);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
FoodtruckInfo foodtruckInfo = new FoodtruckInfo();
//passing the clicked position to the parent class
for (FoodtruckInfo info : foodtruckInfoList) {
if (info.getItemId().equals(foodTruckItemList.get(getAdapterPosition()).getItemId())) {
foodtruckInfo = info;
}
}
listener.onItemClick(foodTruckItemList.get(getAdapterPosition()), foodtruckInfo);
}
}
public PopularItemsAdapter(Context mContext, List<FoodTruckItem> foodTruckItemList, OnItemClickListener listener) {
this.mContext = mContext;
this.foodTruckItemList = foodTruckItemList;
this.listener = listener;
MyCart.getInstance().addListener(this);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_popular_items, parent, false);
return new MyViewHolder(itemView);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final FoodTruckItem foodTruckItem = foodTruckItemList.get(position);
if (SessionManager.get(mContext).getFoodTruckItemList() != null) {
sessionItem = SessionManager.get(mContext).getFoodTruckItemList();
for (FoodTruckItem item : sessionItem) {
if (item.getItemId().equals(foodTruckItem.getItemId())) {
// holder.itemTag.setText("MY FAVOURITE");
holder.itemTag.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_favorite));
}
}
}
holder.itemName.setText(foodTruckItem.getItemName());
// holder.itemTag.setText(foodTruckItem.getSpecialTag());
holder.foodPrice.setText("$" + String.valueOf(foodTruckItem.getItemPrice()));
Picasso.Builder builder = new Picasso.Builder(mContext);
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
if (!TextUtils.isEmpty(foodTruckItem.getItemImg())) {
builder.build().load(foodTruckItem.getItemImg()).into(holder.itemImage);
}
holder.addText.setOnClickListener(new View.OnClickListener() {
FoodtruckInfo info = new FoodtruckInfo();
#Override
public void onClick(View v) {
for (int l = 0; l < foodtruckInfoList.size(); l++) {
if (foodtruckInfoList.get(l).getItemId().equals(foodTruckItem.getItemId())) {
if (foodtruckInfoList.get(l).getOrderStatus() == 0) {
isClickable = true;
} else {
isClickable = false;
}
}
}
if (isClickable) {
String foodTruckId = null;
if (MyCart.getInstance().getFoodTruckId() != null) {
foodTruckId = MyCart.getInstance().getFoodTruckId();
if (!foodTruckId.equals(foodtruckInfoList.get(position).getFoodTruckId())) {
listener.showWarningDialog(position);
} else {
addItem(holder, position, foodTruckItem);
}
} else {
isConflictResolved = false;
addItem(holder, position, foodTruckItem);
}
} else {
listener.showRestaurentClosed();
}
if (isConflictResolved) {
isConflictResolved = false;
addItem(holder, position, foodTruckItem);
}
}
});
holder.addQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = foodTruckItem.getItemQuantityOrdered();
quantity += 1;
holder.quantityText.setText(String.valueOf(quantity));
MyCart.getInstance().updateQuantity(quantity, foodTruckItem.getItemId(), false);
}
});
holder.removeQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = foodTruckItem.getItemQuantityOrdered();
quantity -= 1;
if (quantity == 0) {
MyCart.getInstance().removeItem(foodTruckItem.getItemId(), false);
holder.addLayout.setVisibility(View.INVISIBLE);
holder.addText.setVisibility(View.VISIBLE);
listener.showSnackBar(quantity, false, position);
} else {
holder.quantityText.setText(String.valueOf(quantity));
MyCart.getInstance().updateQuantity(quantity, foodTruckItem.getItemId(), false);
}
}
});
setFontStyle(holder);
}
private void addItem(MyViewHolder holder, int position, FoodTruckItem foodTruckItem) {
holder.addLayout.setVisibility(View.VISIBLE);
holder.addText.setVisibility(View.INVISIBLE);
foodTruckItem.setItemQuantityOrdered(1);
holder.quantityText.setText(String.valueOf(1));
MyCart.getInstance().addItem(foodTruckItem);
MyCart.getInstance().setFoodTruckId(foodtruckInfoList.get(position).getFoodTruckId());
listener.showSnackBar(MyCart.getInstance().getItemList(), true, position);
}
private void setFontStyle(MyViewHolder holder) {
holder.itemName.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
// holder.itemTag.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
holder.foodPrice.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
holder.addText.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
}
#Override
public int getItemCount() {
return foodTruckItemList.size();
}
}
Here addConflictItem() I have written notifyItemChanged , but somehow it is not calling onBindViewHolder , so is there anything missing in the application?
I was having the same problem, and this worked for me, just add those line to your recyclerview declaration, see this Asnswer
DefaultItemAnimator animator = new DefaultItemAnimator() {
#Override
public boolean canReuseUpdatedViewHolder(RecyclerView.ViewHolder viewHolder) {
return true;
}
};
mRecyclerView.setItemAnimator(animator);
As my experience using setOnClickListener in onBindViewHolder is not good idea.
public class PopularItemsAdapter extends RecyclerView.Adapter<PopularItemsAdapter.MyViewHolder>
implements MyCartListener {
private Context mContext;
private List<FoodTruckItem> foodTruckItemList;
private boolean isClickable = false;
private OnItemClickListener listener;
private List<FoodtruckInfo> foodtruckInfoList = new ArrayList<>();
private List<FoodTruckItem> sessionItem = new ArrayList<>();
private boolean isConflictResolved = false;
public int position = -1;
#Override
public void itemUpdated(int quantity, String itemId) {
for (int i = 0; i < foodTruckItemList.size(); i++) {
if (itemId.equals(foodTruckItemList.get(i).getItemId())) {
foodTruckItemList.get(i).setItemQuantityOrdered(quantity);
// notifyDataSetChanged();
}
}
}
#Override
public void itemRemoved(String itemId) {
for (int j = 0; j < foodTruckItemList.size(); j++) {
if (itemId.equals(foodTruckItemList.get(j).getItemId())) {
foodTruckItemList.remove(j);
// notifyDataSetChanged();
}
}
}
public void addConflictItem(int position) {
isConflictResolved = true;
notifyItemChanged(position);
}
public interface OnItemClickListener {
void onItemClick(FoodTruckItem foodTruckItem, FoodtruckInfo foodtruckInfo);
void showSnackBar(int items, boolean added, int position);
void showRestaurentClosed();
void showWarningDialog(int position);
}
public void addFoodInfo(List<FoodtruckInfo> foodtruckInfos) {
foodtruckInfoList.addAll(foodtruckInfos);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView itemName, foodPrice, addText, quantityText, addQuantity, removeQuantity;
public ImageView itemImage, itemTag;
public LinearLayout addLayout;
MyViewHolder holder;
public MyViewHolder(View view) {
super(view);
itemTag = (ImageView) view.findViewById(R.id.itemTag);
itemImage = (ImageView) view.findViewById(R.id.itemImage);
itemName = (TextView) view.findViewById(R.id.itemName);
foodPrice = (TextView) view.findViewById(R.id.foodPrice);
addText = (TextView) view.findViewById(R.id.addText);
addLayout = (LinearLayout) view.findViewById(R.id.addLayout);
quantityText = (TextView) view.findViewById(R.id.quantityText);
addQuantity = (TextView) view.findViewById(R.id.addQuantity);
removeQuantity = (TextView) view.findViewById(R.id.removeQuantity);
holder = this;
view.setOnClickListener(this);
addText.setOnClickListener(new View.OnClickListener() {
FoodtruckInfo info = new FoodtruckInfo();
#Override
public void onClick(View v) {
int position = getAdapterPosition;
for (int l = 0; l < foodtruckInfoList.size(); l++) {
if (foodtruckInfoList.get(l).getItemId().equals(foodTruckItem.getItemId())) {
if (foodtruckInfoList.get(l).getOrderStatus() == 0) {
isClickable = true;
} else {
isClickable = false;
}
}
}
if (isClickable) {
String foodTruckId = null;
if (MyCart.getInstance().getFoodTruckId() != null) {
foodTruckId = MyCart.getInstance().getFoodTruckId();
if (!foodTruckId.equals(foodtruckInfoList.get(position).getFoodTruckId())) {
listener.showWarningDialog(position);
} else {
addItem(holder, position, foodTruckItem);
}
} else {
isConflictResolved = false;
addItem(holder, position, foodTruckItem);
}
} else {
listener.showRestaurentClosed();
}
if (isConflictResolved) {
isConflictResolved = false;
addItem(holder, position, foodTruckItem);
}
}
});
removeQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition;
int quantity = foodTruckItem.getItemQuantityOrdered();
quantity -= 1;
if (quantity == 0) {
MyCart.getInstance().removeItem(foodTruckItem.getItemId(), false);
holder.addLayout.setVisibility(View.INVISIBLE);
holder.addText.setVisibility(View.VISIBLE);
listener.showSnackBar(quantity, false, position);
} else {
holder.quantityText.setText(String.valueOf(quantity));
MyCart.getInstance().updateQuantity(quantity, foodTruckItem.getItemId(), false);
}
}
});
addQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition;
int quantity = foodTruckItem.getItemQuantityOrdered();
quantity += 1;
holder.quantityText.setText(String.valueOf(quantity));
MyCart.getInstance().updateQuantity(quantity, foodTruckItem.getItemId(), false);
}
});
}
#Override
public void onClick(View view) {
FoodtruckInfo foodtruckInfo = new FoodtruckInfo();
//passing the clicked position to the parent class
for (FoodtruckInfo info : foodtruckInfoList) {
if (info.getItemId().equals(foodTruckItemList.get(getAdapterPosition()).getItemId())) {
foodtruckInfo = info;
}
}
listener.onItemClick(foodTruckItemList.get(getAdapterPosition()), foodtruckInfo);
}
}
public PopularItemsAdapter(Context mContext, List<FoodTruckItem> foodTruckItemList, OnItemClickListener listener) {
this.mContext = mContext;
this.foodTruckItemList = foodTruckItemList;
this.listener = listener;
MyCart.getInstance().addListener(this);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_popular_items, parent, false);
return new MyViewHolder(itemView);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final FoodTruckItem foodTruckItem = foodTruckItemList.get(position);
if (SessionManager.get(mContext).getFoodTruckItemList() != null) {
sessionItem = SessionManager.get(mContext).getFoodTruckItemList();
for (FoodTruckItem item : sessionItem) {
if (item.getItemId().equals(foodTruckItem.getItemId())) {
// holder.itemTag.setText("MY FAVOURITE");
holder.itemTag.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_favorite));
}
}
}
holder.itemName.setText(foodTruckItem.getItemName());
// holder.itemTag.setText(foodTruckItem.getSpecialTag());
holder.foodPrice.setText("$" + String.valueOf(foodTruckItem.getItemPrice()));
Picasso.Builder builder = new Picasso.Builder(mContext);
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
if (!TextUtils.isEmpty(foodTruckItem.getItemImg())) {
builder.build().load(foodTruckItem.getItemImg()).into(holder.itemImage);
}
setFontStyle(holder);
}
private void addItem(MyViewHolder holder, int position, FoodTruckItem foodTruckItem) {
holder.addLayout.setVisibility(View.VISIBLE);
holder.addText.setVisibility(View.INVISIBLE);
foodTruckItem.setItemQuantityOrdered(1);
holder.quantityText.setText(String.valueOf(1));
MyCart.getInstance().addItem(foodTruckItem);
MyCart.getInstance().setFoodTruckId(foodtruckInfoList.get(position).getFoodTruckId());
listener.showSnackBar(MyCart.getInstance().getItemList(), true, position);
}
private void setFontStyle(MyViewHolder holder) {
holder.itemName.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
// holder.itemTag.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
holder.foodPrice.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
holder.addText.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
}
#Override
public int getItemCount() {
return foodTruckItemList.size();
}
}
Just call notifyDataSetChanged() and the RecycleView will refresh
I have two buttons: + and -. I want that when I click on the button +, the value of the textview present in the fragment class (outside the listview) is changed. How can I do this ?
This is my Adapter class:
public class CartBaseAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<PojoCart> mList;
private ViewHolder viewHolder;
private HashMap<String, Integer> mHashMap = new HashMap<String, Integer>();
private Integer total;
private DataBaseHandler dbh;
private int Id = 1;
private String value1, value2;
private int z;
private FragmentTransactionListener fragmentTransactionListener = (FragmentTransactionListener) new Cart();
public CartBaseAdapter(Context mContext, ArrayList<PojoCart> mList) {
this.mContext = mContext;
this.mList = mList;
dbh = new DataBaseHandler(mContext);
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.mImgItem = (ImageView) convertView.findViewById(R.id.cart_image);
viewHolder.mTvItemName = (TextView) convertView.findViewById(R.id.tv_item_name);
viewHolder.mTvItemPrice = (TextView) convertView.findViewById(R.id.tv_item_price);
viewHolder.mTvNumber = (TextView) convertView.findViewById(R.id.tv_number);
viewHolder.mBtnAdd = (Button) convertView.findViewById(R.id.btn_add);
viewHolder.mBtnMinus = (Button) convertView.findViewById(R.id.btn_sub);
viewHolder.mImgDelete = (ImageView) convertView.findViewById(R.id.img_del);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
convertView.setTag(viewHolder);
final PojoCart pojoCart = (PojoCart) getItem(position);
viewHolder.mTvItemName.setText(pojoCart.getmItemName());
viewHolder.mTvItemPrice.setText(pojoCart.getmItemPrice());
// viewHolder.mImgDelete.setTag(pojoCart.getmCategoryId());
/* try {
URL url = new URL(pojoCart.getmItemImage());
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
viewHolder.mImgItem.setImageBitmap(bmp);
} catch (Exception e) {
e.printStackTrace();
// Log.e("exception", "" + e.getMessage());
}*/
viewHolder.mImgItem.setImageBitmap(Utility.StringToBitMap(pojoCart.getmItemImage()));
viewHolder.mBtnAdd.setTag(pojoCart);
viewHolder.mBtnMinus.setTag(pojoCart);
viewHolder.mTvItemPrice.setTag(pojoCart);
viewHolder.mTvNumber.setTag(pojoCart);
viewHolder.mImgDelete.setTag(position);
if (pojoCart.getmQuantity() > 0) {
viewHolder.mTvNumber.setText("" + pojoCart.getmQuantity());
} else {
viewHolder.mTvNumber.setText("" + 0);
}
viewHolder.mBtnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PojoCart pojoCart = (PojoCart) v.getTag();
int mValue = pojoCart.getmQuantity();
mValue++;
viewHolder.mTvNumber.setText("" + mValue);
pojoCart.setmQuantity(mValue);
notifyDataSetChanged();
value1 = viewHolder.mTvNumber.getText().toString();
value2 = pojoCart.getmItemPrice();
int x = Integer.parseInt(value1);
int y = Integer.parseInt(value2);
// viewHolder.Dish_rate.setVisibility(View.GONE);
Log.e("value1", value1);
Log.e("value2", value2);
z = x * y;
pojoCart.setmItemPrice(String.valueOf(z));
Log.e("z", "" + z);
if (x > 2) {
int n = x - 1;
int k = z / n;
Log.e("k", "" + k);
pojoCart.setmItemPrice(String.valueOf(k));
} else {
pojoCart.setmItemPrice(String.valueOf(z));
}
dbh.updateSingleRow(pojoCart.getmCategoryId(), pojoCart.getmItemPrice(), pojoCart.getmQuantity());
int total = dbh.getTotalOfAmount();
pojoCart.setmTotalPrice(total);
}
});
viewHolder.mBtnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PojoCart pojoCart = (PojoCart) v.getTag();
int mValue = pojoCart.getmQuantity();
if (mValue > 0) {
mValue--;
viewHolder.mTvNumber.setText("" + mValue);
value1 = viewHolder.mTvNumber.getText().toString();
value2 = pojoCart.getmItemPrice();
int x = Integer.parseInt(value1);
int y = Integer.parseInt(value2);
if (x >= 1) {
Log.e("value11", value1);
Log.e("value22", value2);
int n = x + 1;
Log.e("n", "" + n);
int k = y / n;
Log.e("k", "" + k);
z = k * x;
Log.e("z", "" + z);
pojoCart.setmItemPrice(String.valueOf(z));
} else {
pojoCart.setmItemPrice(pojoCart.getmItemPrice());
}
}
pojoCart.setmQuantity(mValue);
notifyDataSetChanged();
dbh.updateSingleRow(pojoCart.getmCategoryId(), pojoCart.getmItemPrice(), pojoCart.getmQuantity());
pojoCart.setmTotalPrice(dbh.getTotalOfAmount());
}
}
);
viewHolder.mImgDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
int categoryId = pojoCart.getmCategoryId();
// int id = (Integer) view.getTag();
// id++;
Log.e("removeIdFromTheTable", "" + categoryId);
dbh.delete_byID(categoryId);
mList.remove(position);
notifyDataSetChanged();
pojoCart.setmTotalPrice(dbh.getTotalOfAmount());
}
}
);
return convertView;
}
private class ViewHolder {
TextView mTvItemName, mTvItemPrice, mTvNumber;
ImageView mImgItem, mImgDelete;
Button mBtnAdd, mBtnMinus;
}
}
This is my Fragment Class:
public class Cart extends Fragment implements View.OnClickListener {
private ArrayList<PojoCart> mCartList;
private ListView mListView;
private CartBaseAdapter mCartBaseAdapter;
private DataBaseHandler dbh;
private List<PojoCartDataBase> pojoCartDataBase;
private TextView mTvProcesscheck, mTvTotalPrice;
private String ItemName, ItemPrice;
private String ItemImage;
private ArrayList<String> mTotalPrice;
private Toolbar toolbar;
private int ItemQuantity;
int id = 1;
private String categoryId;
private int sumOfPrice;
private PojoCart pojoCart;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_cart, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initialize();
// addData();
displayTotalAmount();
try {
getDataFromDatabase();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initialize() {
mTotalPrice = new ArrayList<String>();
mCartList = new ArrayList<PojoCart>();
mListView = (ListView) getActivity().findViewById(R.id.listview_cart);
mCartBaseAdapter = new CartBaseAdapter(getContext(), mCartList);
Parcelable state = mListView.onSaveInstanceState();
mListView.setAdapter(mCartBaseAdapter);
mListView.onRestoreInstanceState(state);
mTvProcesscheck = (TextView) getActivity().findViewById(R.id.tv_checkout);
mTvTotalPrice = (TextView) getActivity().findViewById(R.id.tv_total_price);
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
dbh = new DataBaseHandler(getContext());
mTvProcesscheck.setOnClickListener(this);
toolbar.setTitle("Cart");
mCartBaseAdapter.notifyDataSetChanged();
final RippleView rippleView = (RippleView) getActivity().findViewById(R.id.ripple_view_cart);
rippleView.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
#Override
public void onComplete(RippleView rippleView) {
Log.d("Sample", "Ripple completed");
Fragment fragment = new LogIn();
getFragmentManager().beginTransaction().replace(R.id.frame, fragment).addToBackStack(null).commit();
toolbar.setTitle("Restaurant List");
}
});
}
/* private void addData() {
for (int i = 0; i < mItemName.length; i++) {
PojoCart pojoCart = new PojoCart();
pojoCart.setmItemName(mItemName[i]);
pojoCart.setmItemPrice(mItemPrice[i]);
pojoCart.setmItemImage(mItemImage[i]);
mCartList.add(pojoCart);
}
// mCartList.add(pojoCartDataBase);
}
*/
private void getDataFromDatabase() throws IOException {
Cursor c = dbh.getAllRows();
if (c.moveToFirst()) {
while (c.isAfterLast() == false) {
// int id = c.getInt(0);
int id = c.getInt(1);
Log.e("id.....", "" + id);
ItemName = c.getString(2);
ItemPrice = c.getString(3);
Log.e("itemname", ItemName);
Log.e("itemprice", ItemPrice);
ItemQuantity = c.getInt(4);
Log.e("itemquantity", "" + ItemQuantity);
ItemImage = c.getString(5);
Log.e("itemimage.........", ItemImage);
pojoCart = new PojoCart();
pojoCart.setmItemName(ItemName);
pojoCart.setmItemPrice(ItemPrice);
pojoCart.setmItemImage(ItemImage);
pojoCart.setmQuantity(ItemQuantity);
pojoCart.setmCategoryId(id);
mCartList.add(pojoCart);
mCartBaseAdapter.notifyDataSetChanged();
c.moveToNext();
}
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_checkout:
/* Fragment fragment = new LogIn();
getFragmentManager().beginTransaction().replace(R.id.frame, fragment).addToBackStack(null).commit();*/
// toolbar.setTitle("Checkout");
}
}
public void displayTotalAmount() {
int total = dbh.getTotalOfAmount();
mTvTotalPrice.setText(String.valueOf(total));
}
}
I want to change the value of the mTvTotalPric (Textview) on click of the button + and -, which is present at the listview. And the textview which the value I want to change is outside the listview.
In your Adapter class create one interface
Adapter.class
public class CartBaseAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<PojoCart> mList;
private ViewHolder viewHolder;
private HashMap<String, Integer> mHashMap = new HashMap<String, Integer>();
private Integer total;
private DataBaseHandler dbh;
private int Id = 1;
private String value1, value2;
private int z;
private FragmentTransactionListener fragmentTransactionListener = (FragmentTransactionListener) new Cart();
private SendDataToFragment sendDataToFragment;
public CartBaseAdapter(FragmentCart fragmentCart, Context mContext, ArrayList<PojoCart> mList) {
this.mContext = mContext;
this.mList = mList;
dbh = new DataBaseHandler(mContext);
sendDataToFragment = (SendDataToFragment) fragmentCart;
}
//Interface to send data from adapter to fragment
public interface SendDataToFragment {
void sendData(String Data);
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.mImgItem = (ImageView) convertView.findViewById(R.id.cart_image);
viewHolder.mTvItemName = (TextView) convertView.findViewById(R.id.tv_item_name);
viewHolder.mTvItemPrice = (TextView) convertView.findViewById(R.id.tv_item_price);
viewHolder.mTvNumber = (TextView) convertView.findViewById(R.id.tv_number);
viewHolder.mBtnAdd = (Button) convertView.findViewById(R.id.btn_add);
viewHolder.mBtnMinus = (Button) convertView.findViewById(R.id.btn_sub);
viewHolder.mImgDelete = (ImageView) convertView.findViewById(R.id.img_del);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
convertView.setTag(viewHolder);
final PojoCart pojoCart = (PojoCart) getItem(position);
viewHolder.mTvItemName.setText(pojoCart.getmItemName());
viewHolder.mTvItemPrice.setText(pojoCart.getmItemPrice());
viewHolder.mImgItem.setImageBitmap(Utility.StringToBitMap(pojoCart.getmItemImage()));
viewHolder.mBtnAdd.setTag(pojoCart);
viewHolder.mBtnMinus.setTag(pojoCart);
viewHolder.mTvItemPrice.setTag(pojoCart);
viewHolder.mTvNumber.setTag(pojoCart);
viewHolder.mImgDelete.setTag(position);
if (pojoCart.getmQuantity() > 0) {
viewHolder.mTvNumber.setText("" + pojoCart.getmQuantity());
} else {
viewHolder.mTvNumber.setText("" + 0);
}
viewHolder.mBtnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Send data via interface to your fragment
sendDataToFragment.sendData("Your Data");
//Your existing code
}
});
viewHolder.mBtnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Send data via interface to your fragment
sendDataToFragment.sendData("Your Data");
//Your existing code
}
});
return convertView;
}
private class ViewHolder {
TextView mTvItemName, mTvItemPrice, mTvNumber;
ImageView mImgItem, mImgDelete;
Button mBtnAdd, mBtnMinus;
}
}
Inside your fragment implement that interface so as soon as your button is clicked in your adapter you will get the data inside your fragment.
Fragment.class
public class FragmentCart extends Fragment implements
View.OnClickListener, CartBaseAdapter.SendDataToFragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_layout, null);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
CartBaseAdapter adapter = new CartBaseAdapter(FragmentCart.this, getActivity(), yourList);
}
#Override
public void onClick(View v) {
}
#Override
public void sendData(String Data) {
//set this data to your textView
}
}
Create a interface :
public interface MyListener {
// you can define any parameter as per your requirement
public void callback(View view, int value);
}
In your listview adapter use interface like below on click of button + or - like :
MyListener ml;
ml = (MyListener) context;
ml.callback(this, "success");
In activity implements MyListener than callback method override there and than you get performed action from fragment to activity.
I have an issue in RecycleView. My screen has two tabs, both tabs contain recycleview.It call normally most of the time but sometimes give empty screen. Just I wrote log & system.out and found this issue. I will paste my adapter class code here.
public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HEADER = 0;
public static final int CHILD = 1;
List<ContentTitle> titles;
Context context;
private List<Item> titleData = new ArrayList<Item>();
public ExpandableListAdapter(List<Item> data) {
this.titleData = data;
System.out.println("===this.titleData===" + this.titleData.size());
}
public void replaceContentFragment(String title,int id,int bookmarked) {
try {
SkillsApp SkillsApp = (SkillsApp) context.getApplicationContext();
Fragment fragment = new ContentActivityFragment();
FragmentManager fragmentManager = skillsUSAApp.mainActivity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
SkillsApp.subtitleID = id;
SkillsApp.isbookmark = (bookmarked == 0)? false:true;
SkillsApp.mainActivity.getSupportActionBar().setTitle(title);
SkillsApp.selectedSubtitleID = id;
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = null;
try{
context = parent.getContext();
final SkillsApp skillsApp = (SkillsAApp)context.getApplicationContext();
if(!skillsApp.isDrawer){
switch (type) {
case HEADER:
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.main_title, parent, false);
ListHeaderViewHolder header = new ListHeaderViewHolder(view);
return header;
case CHILD:
LayoutInflater inflater1 = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater1.inflate(R.layout.sub_title, parent, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("Child", "child");
TextView text = (TextView) view.findViewById(R.id.header_title);
}
});
return new RecyclerView.ViewHolder(view) {
};
}
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
try{
System.out.println("==========##########");
final Item item = titleData.get(position);
final SkillsAApp skillsAApp = (SkillsAApp)context.getApplicationContext();
System.out.println("===onBindViewHolder item===" + item.mainTitle.title);
switch (item.type) {
case HEADER:
final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
itemController.refferalItem = item;
itemController.header_title.setText(item.mainTitle.title);
if (item.invisibleChildren == null) {
itemController.btn_expand_toggle.setImageResource(R.drawable.right_filled_arrow);
} else {
itemController.btn_expand_toggle.setImageResource(R.drawable.right_filled_arrow);
}
itemController.layoutItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
if(!skillsAApp.isDrawer){
if (item.invisibleChildren == null) {
item.invisibleChildren = new ArrayList<Item>();
int count = 0;
int pos = titleData.indexOf(itemController.refferalItem);
while (titleData.size() > pos + 1 && titleData.get(pos + 1).type == CHILD) {
item.invisibleChildren.add(titleData.remove(pos + 1));
count++;
}
notifyItemRangeRemoved(pos + 1, count);
notifyDataSetChanged();
itemController.btn_expand_toggle.setImageResource(R.drawable.right_filled_arrow);
} else {
int pos = titleData.indexOf(itemController.refferalItem);
int index = pos + 1;
for (Item i : item.invisibleChildren) {
titleData.add(index, i);
index++;
}
notifyItemRangeInserted(pos + 1, index - pos - 1);
notifyDataSetChanged();
itemController.btn_expand_toggle.setImageResource(R.drawable.down_arrow);
item.invisibleChildren = null;
}
}
}catch (Exception e){
e.printStackTrace();
}
}
});
break;
case CHILD:
View itemTextView = (View) holder.itemView;
TextView view = (TextView) itemTextView.findViewById(R.id.header_title);
view.setText(titleData.get(position).subtitle.title);
final int pos = position;
itemTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
if(!skillsUSAApp.isDrawer){
TextView text = (TextView) view.findViewById(R.id.header_title);
FlurryAgent.logEvent("Sub Category Item");
replaceContentFragment(text.getText().toString(), titleData.get(pos).subtitle.subtitleId, titleData.get(pos).subtitle.bookMarked);
}
}catch (Exception e){
e.printStackTrace();
}
}
});
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public int getItemViewType(int position) {
return titleData.get(position).type;
}
#Override
public int getItemCount() {
return titleData.size();
}
#Override
public long getItemId(int position) {
return position;
}
private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
public TextView header_title;
public ImageView btn_expand_toggle;
public Item refferalItem;
public RelativeLayout layoutItem;
public ListHeaderViewHolder(View itemView) {
super(itemView);
try{
header_title = (TextView) itemView.findViewById(R.id.header_title);
btn_expand_toggle = (ImageView) itemView.findViewById(R.id.btn_expand_toggle);
layoutItem = (RelativeLayout) itemView.findViewById(R.id.ll_title);
}catch (Exception e){
e.printStackTrace();
}
}
}
public static class Item {
public int type;
public String text;
public ContentTitle mainTitle;
public ContentSubTitle subtitle;
public List<Item> invisibleChildren;
public Item(int type, String text, List<Item> children) {
this.type = type;
this.text = text;
this.invisibleChildren = children;
}
public Item(int type, ContentTitle title,ContentSubTitle stitle) {
this.type = type;
this.mainTitle = title;
this.subtitle=stitle;
}
public Item(int type, String text) {
this.type = type;
this.text = text;
}
}
}
Here is a calling adapter from tab fragment
recyclerview = (RecyclerView) v.findViewById(R.id.recyclerview);
recyclerview.setLayoutManager(new LinearLayoutManager(v.getContext(), LinearLayoutManager.VERTICAL, false));
// recyclerview.setLayoutManager(new LinearLayoutManager(v.getContext()));
ExpandableListAdapter adapter = new ExpandableListAdapter(items);
recyclerview.setAdapter(adapter);
adapter.notifyDataSetChanged();
could you please advice me what is an issue? I didn't get any console error message.Could you please help me anyone here