Nested ArrayList in Android - java

I want to create a cart which has Nested array.
Like my parent array has items and child array has item's respective toppings but when i add toppings to my item array it automatically add same toppings to all index of items array. Here is my image:
Here i'm attaching my code below
Item_Array
private void addNewToppinDialoge(ProductsModel.Datum datum, int adapterPosition) {
ProductOrderModel.Datum productOrderModel = new ProductOrderModel.Datum();
productOrderModel.setCategoryID(datum.getProductID());
productOrderModel.setCategory(datum.getProductName());
int i = productActivity.productOrderModelArrayList.size();
int j = i + 1;
productOrderModel.setSrNO(String.valueOf(j));
productActivity.productOrderModelArrayList.add(productOrderModel);
productActivity.refreshOrderAdapter();
productActivity.changeTitleToolbar(datum.getProductName());
}
Toppings_array
private void addToppingToCart(ToppingsModel.Datum.LookupValue lookupValue, int adapterPosition) {
ProductOrderModel.Datum datum = new ProductOrderModel.Datum();
ProductOrderModel.Datum.SubCategory subCategory = new ProductOrderModel.Datum.SubCategory();
subCategory.setCategory(lookupValue.getLookupvalue());
int pos = productActivity.productOrderModelArrayList.size() - 1;
Log.e("POS", String.valueOf(ProductActivity.productOrderModelArrayList.size() - 1));
productActivity.productOrderModelArrayListSub.add(subCategory);
int subPos = productActivity.productOrderModelArrayListSub.size() - 1;
productActivity.productOrderModelArrayListSub.get(subPos).setCategory(lookupValue.getLookupvalue());
productActivity.productOrderModelArrayList.get(pos).setSubCategory(productActivity.productOrderModelArrayListSub);
productActivity.refreshOrderAdapter();
}
Adapter For Cart
public class MyOrderAdapter extends RecyclerView.Adapter<MyOrderAdapter.ViewHolder> {
public static ToppingsListAdapter toppingsListAdapter;
static Context mContext;
ArrayList<ProductOrderModel.Datum> orderModelArrayList;
public MyOrderAdapter(Context mContext, ArrayList<ProductOrderModel.Datum> orderModelArrayList) {
MyOrderAdapter.mContext = mContext;
this.orderModelArrayList = orderModelArrayList;
}
#NonNull
#Override
public MyOrderAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View mView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.myorder_layout, viewGroup, false);
return new MyOrderAdapter.ViewHolder(mView);
}
#Override
public void onBindViewHolder(#NonNull MyOrderAdapter.ViewHolder holder, int i) {
holder.mTextOrderName.setText(orderModelArrayList.get(i).getCategory());
holder.mImageRemove.setOnClickListener(v -> removeItem(orderModelArrayList.get(i), holder.getAdapterPosition()));
holder.mTextSerialNo.setText(orderModelArrayList.get(i).getSrNO() + ".");
ArrayList<ProductOrderModel.Datum.SubCategory> arrayItem = (ArrayList<ProductOrderModel.Datum.SubCategory>) orderModelArrayList.get(i).getSubCategory();
if (arrayItem == null) {
} else {
toppingsListAdapter = new ToppingsListAdapter(mContext, arrayItem);
holder.mRecyclerToppings.setAdapter(toppingsListAdapter);
}
}
protected void removeItem(ProductOrderModel.Datum productOrderModel, int adapterPosition) {
}
#Override
public int getItemCount() {
return orderModelArrayList.size();
}
public void refreshAdapter() {
toppingsListAdapter.notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public RecyclerView mRecyclerToppings;
private TextView mTextOrderName, mTextSerialNo;
private ImageView mImageRemove;
public ViewHolder(#NonNull View itemView) {
super(itemView);
mTextOrderName = itemView.findViewById(R.id.orderItemName);
mImageRemove = itemView.findViewById(R.id.orderRemove);
mTextSerialNo = itemView.findViewById(R.id.srno);
mRecyclerToppings = itemView.findViewById(R.id.text_toppings);
RecyclerView.LayoutManager manager = new LinearLayoutManager(mContext, LinearLayout.VERTICAL, false);
mRecyclerToppings.setLayoutManager(manager);
}
public int getAdapterPosition(ProductOrderModel.Datum.SubCategory remove) {
return 0;
}
}
}
strong text:

I guess you need to header and footer of RecyclerView. Here is the code.
Try this one:
public class HeaderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
String[] data;
public HeaderAdapter(String[] data) {
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_ITEM) {
//inflate your layout and pass it to view holder
return new VHItem(null);
} else if (viewType == TYPE_HEADER) {
//inflate your layout and pass it to view holder
return new VHHeader(null);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof VHItem) {
String dataItem = getItem(position);
//cast holder to VHItem and set data
} else if (holder instanceof VHHeader) {
//cast holder to VHHeader and set data for header.
}
}
#Override
public int getItemCount() {
return data.length + 1;
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
private boolean isPositionHeader(int position) {
return position == 0;
}
private String getItem(int position) {
return data[position - 1];
}
class VHItem extends RecyclerView.ViewHolder {
TextView title;
public VHItem(View itemView) {
super(itemView);
}
}
class VHHeader extends RecyclerView.ViewHolder {
Button button;
public VHHeader(View itemView) {
super(itemView);
}
}
}

Related

Cast exception on multiple viewholder recyclerview

i used multiple viewholder in DataListAdapter.
each holder have a adapter.
my adapter :
public class DataListAdapter extends BaseAdapter<HomeListItem> {
private RecyclerView.RecycledViewPool pool;
public static final int ADS = 10, DATA = 11, PIC = 13, QUE=14;
public DataListAdapter(ArrayList<HomeListItem> dataList, AdapterListener<HomeListItem> listener) {
this.dataList = dataList;
this.listener = listener;
pool = new RecyclerView.RecycledViewPool();
}
#Override
public void onViewRecycled(#NonNull BaseViewHolder holder) {
super.onViewRecycled(holder);
}
#NonNull
#Override
public BaseViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == ADS){
return new ADSDataHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_home_ads, parent, false));
}else if (viewType == PIC) {
return new PictureHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_home, parent, false));
}else if (viewType == QUE) {
return new QuestionHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_home, parent, false));
}else
return new DataHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_home, parent, false));
}
#Override
public int getItemViewType(int position) {
if (dataList.get(position).getType() == ContentType.ADS)
return ADS;
if (dataList.get(position).getType() == ContentType.GALLERY)
return PIC;
if (dataList.get(position).getType() == ContentType.LIBS )
return DATA;
return QUE;
}
#Override
public void onBindViewHolder(#NonNull BaseViewHolder holder, int position) {
if (holder instanceof DataHolder){
((DataHolder) holder).bind(dataList.get(position));
} else if (holder instanceof ADSDataHolder) {
((ADSDataHolder) holder).bind(dataList.get(position));
} else if (holder instanceof PictureHolder) {
((PictureHolder) holder).bind(dataList.get(position));
}else if (holder instanceof QuestionHolder) {
((QuestionHolder) holder).bind(dataList.get(position));
}
}
class ADSDataHolder extends BaseViewHolder {
...
}
class PictureHolder extends BaseViewHolder {
...
}
class QuestionHolder extends BaseViewHolder{
private RecyclerView recyclerView;
private TextView title;
private View more;
public QuestionHolder(View itemView) {
super(itemView);
setType(QUE);
more = itemView.findViewById(R.id.more);
title = itemView.findViewById(R.id.title);
recyclerView = itemView.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(itemView.getContext(),RecyclerView.HORIZONTAL,false));
recyclerView.hasFixedSize();
recyclerView.setRecycledViewPool(pool);
}
public void bind(HomeListItem data) {
Collections.reverse(data.getData());
title.setText(data.getType().getVisibleName());
HomeQuestionAdapter adapter = new HomeQuestionAdapter((ArrayList<MainPageItem>) (ArrayList<?>) data.getData(),
new AdapterListener<MainPageItem>() {
#Override
public void onItemClick(MainPageItem item) {
onListItemClick(itemView.getContext(), data.getType(), item.getItemId());
}
});
recyclerView.setAdapter(adapter);
more.setOnClickListener(v -> listener.onItemClick(data));
}
}
class DataHolder extends BaseViewHolder {
private RecyclerView recyclerView;
private TextView title;
private View more;
DataHolder(View itemView) {
super(itemView);
setType(DATA);
more = itemView.findViewById(R.id.more);
title = itemView.findViewById(R.id.title);
recyclerView = itemView.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(itemView.getContext(),
LinearLayoutManager.HORIZONTAL, true));
recyclerView.hasFixedSize();
recyclerView.setRecycledViewPool(pool);
}
public void bind(HomeListItem data) {
Collections.reverse(data.getData());
title.setText(data.getType().getVisibleName());
SmallItemAdapter adapter = new SmallItemAdapter((ArrayList<MainPageItem>)
(ArrayList<?>) data.getData(),
new AdapterListener<MainPageItem>() {
#Override
public void onItemClick(MainPageItem item) {
onListItemClick(itemView.getContext(), data.getType(), item.getItemId());
}
});
recyclerView.setAdapter(adapter);
recyclerView.scrollToPosition(data.getData().size() - 1);
more.setOnClickListener(v -> listener.onItemClick(data));
}
}
private void onListItemClick(Context context, ContentType contentType, long id) {
// click
}
}
BaseAdapter:
public abstract class BaseAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
protected List<T> dataList;
protected final int DATA_TYPE = 1;
protected boolean isLoading = false, isMoreDataAvailable = false;
protected AdapterListener<T> listener;
#Override
public int getItemViewType(int position) {
if (dataList.get(position) == null)
return -1;
else return DATA_TYPE;
}
#Override
public int getItemCount() {
return dataList.size();
}
public void setMoreDataAvailable(boolean isMoreDataAvailable) {
this.isMoreDataAvailable = isMoreDataAvailable;
}
public void removeLoadingItem() {
if (dataList.size() > 0 && dataList.get(dataList.size() - 1) == null) {
dataList.remove(dataList.size() - 1);
notifyItemRemoved(dataList.size() - 1);
}
}
public void notifyDataChanged() {
isLoading = false;
notifyDataSetChanged();
}
}
and BaseViewHolder:
public class BaseViewHolder extends RecyclerView.ViewHolder {
private int type;
public BaseViewHolder(View itemView) {
super(itemView);
}
}
when i scroll the recyclerview gives me an error
my error:
:00:26.247 4194-4194/ir.hnfadak.shahidezendeh E/PushPole:Exception caught
java.lang.ClassCastException: ir.hfadak.fadakmedia.UI.Main.Home.Picture.SmallItemAdapter$DataHolder cannot be cast to ir.hfadak.fadakmedia.UI.Main.Question.HomeQuestionAdapter$DataQueHolder
at ir.hfadak.fadakmedia.UI.Main.Question.HomeQuestionAdapter.onBindViewHolder(HomeQuestionAdapter.java:31)
at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
at androidx.recyclerview.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:288)
at androidx.recyclerview.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:345)
at androidx.recyclerview.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:361)
at androidx.recyclerview.widget.GapWorker.prefetch(GapWorker.java:368)
at androidx.recyclerview.widget.GapWorker.run(GapWorker.java:399)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
and my HomeQuestionAdapter
public class HomeQuestionAdapter extends RecyclerView.Adapter<HomeQuestionAdapter.DataQueHolder> {
private RoundedCorners roundedCorners;
protected List<MainPageItem> dataList;
protected final int DATA_TYPE = 1;
protected boolean isLoading = false, isMoreDataAvailable = false;
protected AdapterListener<MainPageItem> listener;
public HomeQuestionAdapter(ArrayList<MainPageItem> dataList, AdapterListener<MainPageItem> listener) {
this.dataList = dataList;
this.listener = listener;
roundedCorners = new RoundedCorners(16);
}
#Override
public int getItemViewType(int position) {
if (dataList.get(position) == null)
return -1;
else return DATA_TYPE;
}
#Override
public int getItemCount() {
return dataList.size();
}
public void setMoreDataAvailable(boolean isMoreDataAvailable) {
this.isMoreDataAvailable = isMoreDataAvailable;
}
public void removeLoadingItem() {
if (dataList.size() > 0 && dataList.get(dataList.size() - 1) == null) {
dataList.remove(dataList.size() - 1);
notifyItemRemoved(dataList.size() - 1);
}
}
public void notifyDataChanged() {
isLoading = false;
notifyDataSetChanged();
}
#NonNull
#Override
public HomeQuestionAdapter.DataQueHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new DataQueHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list_simple_question, parent, false));
}
#Override
public void onBindViewHolder(#NonNull HomeQuestionAdapter.DataQueHolder holder, int position) {
if (!isLoading && isMoreDataAvailable && position >= getItemCount() - 1) {
isLoading = true;
listener.onLoadMore();
} else {
holder.bind(dataList.get(position));
}
}
class DataQueHolder extends RecyclerView.ViewHolder {
private ImageView image;
private ImageView share,faivorid;
private TextView question,answer,view;
DataQueHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.imageQue);
question = itemView.findViewById(R.id.titleQue);
answer = itemView.findViewById(R.id.answerQue);
share = itemView.findViewById(R.id.share);
faivorid = itemView.findViewById(R.id.favorite);
view = itemView.findViewById(R.id.viewtxt);
}
void bind(MainPageItem data) {
Glide.with(itemView)
.load(data.getItemSmallImageAddress())
.apply(bitmapTransform(roundedCorners))
.apply(new RequestOptions().error(R.drawable.img_list_def)
.placeholder(R.drawable.img_list_def))
.into(image);
question.setText(data.getItemTitle());
answer.setText(data.getItemDescription());
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ContextUtil.share(itemView.getContext(),
data.getItemTitle() + "\n\n"
+ data.getItemDescription() + "\n\n"
+ data.getItemSmallImageAddress());
}
});
itemView.setOnClickListener(v -> listener.onItemClick(data));
}
}
}
Where does the code is wrong?
Your are type casting instance of super class to a reference of sub class which is causing this error.
Instead create something like this:-
public void onBindViewHolder(#NonNull BaseViewHolder holder, int position) {
if (holder instanceof DataQueHolder){
((DataQueHolder) holder).bind(dataList.get(position));
}else if (holder instanceof DataHolder){
((DataHolder) holder).bind(dataList.get(position));
}else if (holder instanceof ADSDataHolder) {
((ADSDataHolder) holder).bind(dataList.get(position));
} else if (holder instanceof PictureHolder) {
((PictureHolder) holder).bind(dataList.get(position));
}else if (holder instanceof QuestionHolder) {
((QuestionHolder) holder).bind(dataList.get(position));
}
}
Please remove this below line from DataListAdapter
recyclerView.setRecycledViewPool(pool);
It works for me..

Multiple type of views in Recycler View not setting correctly

I have two array list and want to set the adapter so that it looks like below screen one. But when I am setting adapter I am getting view like second screen. This is my code of Adapter:
public class ItemArrayAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
final int VIEW_TYPE_MESSAGE = 0;
final int VIEW_TYPE_IMAGE = 1;
private static final String TAG = "ItemArrayAdapter";
Context context;
ArrayList<BeforLoginDao.Article> mArticleList;
ArrayList<BeforLoginDao.Quiz> mQuizList;
int i=0;
public ItemArrayAdapter(Context context,ArrayList<BeforLoginDao.Quiz> mQuizList, ArrayList<BeforLoginDao.Article> mArticleList ){
this.context = context;
this.mArticleList = mArticleList;
this.mQuizList = mQuizList;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View itemView;
if(viewType == VIEW_TYPE_MESSAGE){
itemView= LayoutInflater.from(parent.getContext()).inflate(R.layout.article_layout,parent,false);
return new ArticleViewHolder(itemView);
}
else if(viewType == VIEW_TYPE_IMAGE){
itemView= LayoutInflater.from(parent.getContext()).inflate(R.layout.quiz,parent,false);
return new QuizViewHolder(itemView);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position){
Log.e(TAG, "onBindViewHolder: " +position);
if(viewHolder instanceof ArticleViewHolder){
((ArticleViewHolder) viewHolder).populate(mArticleList.get(position));
}
else if(viewHolder instanceof QuizViewHolder){
((QuizViewHolder) viewHolder).populate(mQuizList.get(position - mArticleList.size()));
}
}
#Override
public int getItemCount(){
return mArticleList.size() + mQuizList.size();
}
#Override
public int getItemViewType(int position){
Log.e(TAG, "getItemViewType: " +position );
if(position < mArticleList.size()){
return VIEW_TYPE_MESSAGE;
}
if(position - mArticleList.size() < mQuizList.size()){
return VIEW_TYPE_IMAGE;
}
return -1;
}
public class ArticleViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle, mTag1, mTag2 ;
ImageView mImageView;
public ArticleViewHolder(View itemView) {
super(itemView);
mTitle = itemView.findViewById(R.id.tv_article_title);
mTag1 = itemView.findViewById(R.id.tv_article_tag1);
mTag2 = itemView.findViewById(R.id.tv_article_tag2);
mImageView=itemView.findViewById(R.id.img_article);
}
public void populate(BeforLoginDao.Article chatWrapper){
mTitle.setText(chatWrapper.articleTitle.toString());
mTag1.setText(chatWrapper.subtag1);
mTag2.setText(chatWrapper.subtag2);
}
}
public class QuizViewHolder extends RecyclerView.ViewHolder {
public TextView tvQuizTitle, tvQuizTag1, tvQuizTag2 ;
public QuizViewHolder(View itemView) {
super(itemView);
tvQuizTitle = itemView.findViewById(R.id.tv_quiz_title);
tvQuizTag1 =itemView.findViewById(R.id.tv_quiz_tag1);
tvQuizTag2=itemView.findViewWithTag(R.id.tv_quiz_tag2);
}
public void populate(BeforLoginDao.Quiz imageDataWrapper){
Log.e(TAG, "ViewHolderTwo: " +imageDataWrapper.toString() );
tvQuizTitle.setText(imageDataWrapper.quizTitle);
tvQuizTag1.setText(imageDataWrapper.quiz_subtag1);
}
}
}
To solve this error I also checked many solution on SO.
Ref: enter link description here
Below is screen one and screen two. Screen one that I need, Screen two that I am getting.

How to change one adapter value from another adapter?

I have a little bit problem.In my activity there is two Adapter one is for color selection and another is for size selection. While i clicked one of the item of color then recently the available size adapter should be change but i got problem in size adapter. it changes only when i click the size item. I research and try to solve problem but it doesnt works for me.
Here is my code.
AddToCartActivity.java
public class AddToCartActivity extends BaseActivity{
#Override
protected int getLayout() {
return R.layout.activity_add_to_cart;
}
#Override
protected void init() {
//api called here
}
// response of api
#Override
public void productDetail(ProductCommonModel productCommonModel,
ArrayList<ProductChildModel> productChildModels, HashMap<Integer,
ArrayList<ChildAttributeModel>> childWithAttribute, HashMap<Integer,
ArrayList<ChildImageModel>> childWithImages,
ArrayList<com.hazesoft.dokan.singleproductdetail.model.ColorModel>
colorModels, ArrayList<SizeModel> sizeModels,
ArrayList<RelatedProductModel> relatedProductModels) {
this.productCommonModel = productCommonModel;
this.productChildModels = productChildModels;
this.childWithAttribute = childWithAttribute;
this.childWithImages = childWithImages;
this.colorModels = colorModels;
this.sizeModels = sizeModels;
this.relatedProductModels = relatedProductModels;
tvProductName.setText(productCommonModel.getName());
if (productCommonModel.getSpecialPrice() == 0) {
tvSellingPrice.setText(getString(R.string.rs) + productCommonModel.getSellingPrice());
tvDiscount.setVisibility(View.GONE);
tvSpecialPrice.setVisibility(View.GONE);
} else {
tvSpecialPrice.setText(getString(R.string.rs) + productCommonModel.getSpecialPrice());
tvSellingPrice.setText(getString(R.string.rs) + productCommonModel.getSellingPrice());
tvSellingPrice.setPaintFlags(tvSellingPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
tvDiscount.setText(productCommonModel.getDiscount() + getString(R.string.percentage));
}
setChildDetail(childWithAttribute, productChildModels);
setColorModel(colorModels);
setSizeModel(sizeModels);
quantity = Integer.parseInt(tvQuantityCart.getText().toString());
}
// setcolor adapter
private void setColorModel(ArrayList<ColorModel> colorModels) {
MyColorGridViewAdapter adapter = new MyColorGridViewAdapter(this, colorModels);
gvColor.setAdapter(adapter);
gvColor.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.setSelectedPostion(position);
adapter.notifyDataSetChanged();
}
});
}
// set size adapter
private void setSizeModel(ArrayList<SizeModel> sizeModels) {
sizeCustomModels = new ArrayList<>();
for(int i=0;i<sizeModels.size();i++){
sizeCustomModels.add(new SizeCustomModel(sizeModels.get(i).getAttName(),0));
}
setCustomSizeModelToAdapter(sizeCustomModels);
}
// this is code when i click color and change the size adapter but size doesnt change recently only changes when i click any item of the size
public void getSelectedC0lor(String color) {
selectedColor = color;
selectedSize=null;
sizeCustomModels = new ArrayList<>();
availableSize = new ArrayList<>();
for (int i = 0; i < skuColorSIzeList.size(); i++) {
if (skuColorSIzeList.get(i).getColor().equals(selectedColor)) {
availableSize.add(skuColorSIzeList.get(i).getSize());
}
}
for(int i=0;i<sizeModels.size();i++){
String size = null;
int status=0;
for(int j=0;j<availableSize.size();j++){
if(sizeModels.get(i).getAttName().equals(availableSize.get(j))){
size = sizeModels.get(i).getAttName();
status = 1;
break;
}else {
size = sizeModels.get(i).getAttName();
status = 0;
}
}
sizeCustomModels.add(new SizeCustomModel(size,status));
}
sizeRecylerAdapter.getNewModel(sizeCustomModels);
/*sizeRecylerAdapter = new MyCustomSizeRecylerAdapter(sizeCustomModels,this);
rvSize.setAdapter(sizeRecylerAdapter);
sizeRecylerAdapter.notifyDataSetChanged();*/
/*setCustomSizeModelToAdapter(sizeCustomModels);*/
}
}
MyColorGridViewAdapter.java
public class MyColorGridViewAdapter extends BaseAdapter {
Context context;
List<ColorModel> colorModelList;
String select_color;
boolean ch =false;
int checkPosition = -1;
public MyColorGridViewAdapter(Context context, List<ColorModel> colorModelList) {
this.context = context;
this.colorModelList = colorModelList;
}
public void setSelectedPostion(int postion){
this.checkPosition = postion;
}
#Override
public int getCount() {
return colorModelList.size();
}
#Override
public Object getItem(int position) {
return colorModelList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView==null){
convertView = LayoutInflater.from(context).inflate(R.layout.custom_color_list_item,null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
Picasso.with(context).load(colorModelList.get(position).getImage()).into(holder.ivImage);
holder.tvColorName.setText(colorModelList.get(position).getAttName());
if(checkPosition==position){
holder.ivChecked.setVisibility(View.VISIBLE);
select_color = colorModelList.get(position).getAttName();
if( context instanceof AddToCartActivity){
((AddToCartActivity) context).getSelectedC0lor(select_color);
}
}else {
holder.ivChecked.setVisibility(View.GONE);
}
if(colorModelList.size()==1){
holder.ivChecked.setVisibility(View.VISIBLE);
select_color = colorModelList.get(position).getAttName();
if( context instanceof AddToCartActivity){
((AddToCartActivity) context).getSelectedC0lor(select_color);
}
}
return convertView;
}
class ViewHolder{
#BindView(R.id.view)
LinearLayout view;
#BindView(R.id.tv_color_name)
TextViewHelper tvColorName;
#BindView(R.id.iv_image)
ImageView ivImage;
#BindView(R.id.iv_checked)
ImageView ivChecked;
public ViewHolder(View view) {
ButterKnife.bind(this,view);
}
}
}
MyCustomSizeRecylerAdapter.java
public class MyCustomSizeRecylerAdapter extends RecyclerView.Adapter<MyCustomSizeRecylerAdapter.MyViewHolder> {
ArrayList<SizeCustomModel> sizeModels;
Context context;
int checkPosition = -1;
String selectedSize;
public MyCustomSizeRecylerAdapter(ArrayList<SizeCustomModel> sizeModels, Context context) {
this.sizeModels = sizeModels;
this.context = context;
}
public void getNewModel(ArrayList<SizeCustomModel> customModels) {
sizeModels.clear();
this.sizeModels = customModels;
selectedSize = null;
Log.d("sizemodel", "getNewModel: " + new Gson().toJson(sizeModels));
notifyDataSetChanged();
}
public void getSelectedPosition(int position) {
checkPosition = position;
notifyDataSetChanged();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.size_adapter, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv_sizeName.setText(sizeModels.get(position).getSize());
holder.ll_sizeAdapter.setBackgroundResource(R.drawable.ellipse_register);
if (sizeModels.get(position).getStock_Status() == 0) {
holder.ll_mainview.setClickable(false);
holder.ll_sizeAdapter.setBackgroundResource(R.color.blue_700);
} else if (sizeModels.get(position).getStock_Status() == 1) {
holder.ll_sizeAdapter.setBackgroundResource(R.drawable.ellipse_register);
if (checkPosition == position) {
holder.ll_sizeAdapter.setBackgroundResource(R.drawable.ellipse_green);
holder.tv_sizeName.setTextColor(context.getResources().getColor(R.color.white));
selectedSize = sizeModels.get(position).getSize();
if (context instanceof AddToCartActivity) {
((AddToCartActivity) context).getSelectSize(selectedSize);
}
} else {
holder.ll_sizeAdapter.setBackgroundResource(R.drawable.ellipse_register);
holder.tv_sizeName.setTextColor(context.getResources().getColor(R.color.tv_black));
}
if (sizeModels.size() == 1) {
holder.ll_sizeAdapter.setBackgroundResource(R.drawable.ellipse_green);
holder.tv_sizeName.setTextColor(context.getResources().getColor(R.color.white));
selectedSize = sizeModels.get(position).getSize();
if (context instanceof AddToCartActivity) {
((AddToCartActivity) context).getSelectSize(selectedSize);
}
}
}
}
#Override
public int getItemCount() {
return sizeModels.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.tv_sizeName)
TextView tv_sizeName;
#BindView(R.id.ll_sizeAdapter)
LinearLayout ll_sizeAdapter;
#BindView(R.id.main_view)
LinearLayout ll_mainview;
public MyViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
At first both adapter will set data and after click color item the size adapter must be change but it only changes when i click any of the item. adapter.notifyDataSetChanged() doesnt work here for me.
Both Adapter set
When i click color item but doesnt change size adapter
when i click size item only change size adapter
Use Interface to bridge with two adapter and communicate with each other.

Recyclerview holder mixes on scroll

When scroll recyclerview some items mixes. After I add ads after every 15 items, holder get wrong data. Some items are vip items. I will change background color of these items. But when I scroll it dublicates mixes. How can I solve?
This is my adapter
private Context mCtx;
private List<Car> carList;
private RecyclerViewAnimator mAnimator;
private int AD_TYPE=1;
private int CONTENT_TYPE=2;
private int LIST_AD_DELTA=15;
public ProductAllCarAdapter(RecyclerView recyclerView,Context mCtx, List<Car> carList) {
this.mCtx = mCtx;
this.carList = carList;
mAnimator = new RecyclerViewAnimator(recyclerView);
}
#Override
public ProductAllCarAdapter.ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == AD_TYPE){
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_add_item, null);
ProductAllCarAdapter.ProductViewHolder vh = new ProductAllCarAdapter.ProductViewHolder(itemView);
mAnimator.onCreateViewHolder(itemView);
return vh;
} else {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_car_item, null);
ProductAllCarAdapter.ProductViewHolder vh = new ProductAllCarAdapter.ProductViewHolder(itemView);
mAnimator.onCreateViewHolder(itemView);
return vh;
}
}
#Override
public int getItemViewType(int position) {
if (position>0 && position % LIST_AD_DELTA == 0)
return AD_TYPE;
return CONTENT_TYPE;
}
#Override
public void onBindViewHolder(ProductAllCarAdapter.ProductViewHolder holder, int position) {
if (getItemViewType(position) == CONTENT_TYPE) {
final Car car = carList.get(holder.getAdapterPosition());
GlideApp.with(mCtx).load(car.getImg()).into(holder.imageView);
if (car.getVip() == 1) {
holder.relativeLayout.setBackgroundColor(ContextCompat.getColor(mCtx, R.color.colorVip));
holder.imageViewVIP.setVisibility(View.VISIBLE);
}
final String carid = String.valueOf(car.getCarid());
mAnimator.onBindViewHolder(holder.itemView, position);
} else {
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Context mcontext = view.getContext();
Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(mcontext, android.R.anim.fade_in, android.R.anim.fade_out).toBundle();
Intent intent = new Intent(mcontext, AdsItem.class);
mcontext.startActivity(intent, bundle);
}
});
mAnimator.onBindViewHolder(holder.itemView, position);
}
}
private int getRealPosition(int position) {
if (LIST_AD_DELTA == 0) {
return position;
} else {
return position - position / LIST_AD_DELTA;
}
}
#Override
public long getItemId(int position) { return position; }
#Override
public int getItemCount() {
int additionalContent = 0;
if (carList.size() > 0 && carList.size() > LIST_AD_DELTA) {
additionalContent = ( carList.size() / LIST_AD_DELTA);
}
return carList.size() + additionalContent;
}
public static class ProductViewHolder extends RecyclerView.ViewHolder {
private View mView;
ImageView imageView, imageViewVIP;
RelativeLayout relativeLayout;
public ProductViewHolder(View itemView) {
super(itemView);
mView = itemView;
imageView = itemView.findViewById(R.id.imageView);
imageViewVIP = itemView.findViewById(R.id.imageViewVIP);
relativeLayout = itemView.findViewById(R.id.relativeLayoutpc);
}
public void setOnClickListener(View.OnClickListener listener) {
mView.setOnClickListener(listener);
}
}
I think problem onBindViewHolder function use wrong holder. ArrayList also return true value but on scroll it mixes.
You just have to add the corresponding else of the following if statement block.
if (car.getVip() == 1) {
holder.relativeLayout.setBackgroundColor(ContextCompat.getColor(mCtx, R.color.colorVip));
holder.imageViewVIP.setVisibility(View.VISIBLE);
} else {
holder.relativeLayout.setBackgroundColor(ContextCompat.getColor(mCtx, R.color.colorNormal));
holder.imageViewVIP.setVisibility(View.GONE);
}
This is inside your onBindViewHolder function where the view type is CONTENT_TYPE.
Hope that solves your problem.

Show different view at end of recyclerview in every section like paytm

I have a created this design. Which consists of list of list.
Now I wanted to add a view as "See All" in every section at the end of every recycler view. I wanted like this which is done by paytm.
Here is my code. I have two recyclerview one is vertical and another is horizontal. Here is my BaseRowAdapter which contains another recyclerview.
BaseRowAdapter.java
public class BaseRowAdapter extends RecyclerView.Adapter<BaseRowAdapter.ViewHolder> {
public ArrayList<MainType> types;
private Context context;
private LayoutInflater layoutInflater;
public BaseRowAdapter(ArrayList<MainType> types, Context context) {
this.types = types;
this.context = context;
this.layoutInflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.vertical_scroll_single_entry, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.recyclerView.setAdapter(new BaseRowItemAdapter(context, types.get(position).list));
holder.recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
holder.recyclerView.setHasFixedSize(true);
holder.tvHeading.setText(types.get(position).name);
}
#Override
public int getItemCount() {
return types.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
RecyclerView recyclerView;
TextView tvHeading;
public ViewHolder(View itemView) {
super(itemView);
recyclerView = (RecyclerView) itemView.findViewById(R.id.rvItems);
tvHeading = (TextView) itemView.findViewById(R.id.tvHeading);
}
}
}
And for Inner recyclerview I have to show see more layout at the end. I have done something like this. which result into crashing app.
BaseRowItemAdapter.java
public class BaseRowItemAdapter extends RecyclerView.Adapter<BaseRowItemAdapter.CustomViewHolder> {
private Context context;
private ArrayList<SubType> subTypes;
private LayoutInflater inflater;
public BaseRowItemAdapter(Context context, ArrayList<SubType> subTypes) {
this.context = context;
this.subTypes = subTypes;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getItemViewType(int position) {
return (position == subTypes.size()) ? R.layout.see_more : R.layout.single_item_card;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if (viewType == R.layout.single_item_card) {
view = inflater.inflate(R.layout.single_item_card, parent, false);
} else {
view = inflater.inflate(R.layout.see_more, parent, false);
}
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
SubType subType = subTypes.get(position);
if (position != subTypes.size()) {
holder.tvProductName.setText(subType.name);
Picasso.with(context).load(subType.image).into(holder.ivProduct);
if (!subType.disc.equals("0")) {
holder.tvDiscountPercentage.setText(subType.disc + "%");
holder.tvActualAmount.setPaintFlags(holder.tvActualAmount.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
int a = Integer.parseInt(subType.amount);
float b = Float.parseFloat(subType.disc) / 100;
holder.tvActualAmount.setText("₹ " + subType.amount);
int c = (int) (a * b);
holder.tvDiscountAmount.setText("₹ " + c);
} else {
holder.tvDiscountPercentage.setBackgroundColor(Color.parseColor("#ffffff"));
holder.tvActualAmount.setText("₹ " + subType.amount);
}
} else {
holder.seeMore.setText("See More >>");
}
}
#Override
public int getItemCount() {
return subTypes.size()+1;
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
public ImageView ivProduct;
public TextView tvProductName, tvActualAmount, tvDiscountAmount, tvDiscountPercentage, seeMore;
public CustomViewHolder(View itemView) {
super(itemView);
tvProductName = (TextView) itemView.findViewById(R.id.tvProductName);
tvActualAmount = (TextView) itemView.findViewById(R.id.tvActualAmount);
tvDiscountAmount = (TextView) itemView.findViewById(R.id.tvDiscountAmount);
tvDiscountPercentage = (TextView) itemView.findViewById(R.id.tvDiscountPercentage);
ivProduct = (ImageView) itemView.findViewById(R.id.ivProduct);
seeMore = (TextView) itemView.findViewById(R.id.seeMore);
}
}
}
Here are my both model classes.
public class SubType {
public int id;
public String typeId;
public String name;
public String image;
public String unit;
public String amount;
public String disc;
}
public class MainType {
public int id;
public String name;
public ArrayList<SubType> list;
}
My few logcat details
java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.ashishkudale.linksolution.adapters.BaseRowItemAdapter.onBindViewHolder(BaseRowItemAdapter.java:54)
at com.ashishkudale.linksolution.adapters.BaseRowItemAdapter.onBindViewHolder(BaseRowItemAdapter.java:23)
It is crashing because of IndexOutOfBoundsException. I don't know how to solve this please help.
Change your onBindViewHolder
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
if (position != subTypes.size()) {
SubType subType = subTypes.get(position);
holder.tvProductName.setText(subType.name);
Picasso.with(context).load(subType.image).into(holder.ivProduct);
if (!subType.disc.equals("0")) {
holder.tvDiscountPercentage.setText(subType.disc + "%");
holder.tvActualAmount.setPaintFlags(holder.tvActualAmount.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
int a = Integer.parseInt(subType.amount);
float b = Float.parseFloat(subType.disc) / 100;
holder.tvActualAmount.setText("₹ " + subType.amount);
int c = (int) (a * b);
holder.tvDiscountAmount.setText("₹ " + c);
} else {
holder.tvDiscountPercentage.setBackgroundColor(Color.parseColor("#ffffff"));
holder.tvActualAmount.setText("₹ " + subType.amount);
}
} else {
holder.seeMore.setText("See More >>");
}
}

Categories