SectionedRecyclerView over Write first item - java

I'm Trying to use : SimpleSectionedRecyclerViewAdapter , i have arrayList that have 30 elements with strings , i'm going to group every 10 elements with header Title ,
first item should be "Item0" with header name "First 10 elements start"
but when doing that i get :
"First 10 elements start" // header titile
"Item1" <---! note : it should "Item0"
so where is index number 0 gone?
//adapter.addItem3(CategoriesList.get(0));
List<SimpleSectionedRecyclerViewAdapter.Section> sections =
new ArrayList<SimpleSectionedRecyclerViewAdapter.Section>();
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(0, "First 10 elements start"));
//Add your adapter to the sectionAdapter
SimpleSectionedRecyclerViewAdapter.Section[] dummy = new SimpleSectionedRecyclerViewAdapter.Section[sections.size()];
SimpleSectionedRecyclerViewAdapter mSectionedAdapter = new
SimpleSectionedRecyclerViewAdapter(activity, R.layout.drawer_header_book, R.id.headerName, adapter);
mSectionedAdapter.setSections(sections.toArray(dummy));
mDrawerList.setLayoutManager(new LinearLayoutManager(activity));
mDrawerList.setAdapter(mSectionedAdapter);
I'm using exactly as adapter :
https://gist.github.com/gabrielemariotti/4c189fb1124df4556058
public class DrawerItemCustomAdapterForAllBooks extends RecyclerView.Adapter<DrawerItemCustomAdapterForAllBooks.SimpleViewHolder> {
private final Context context;
Typeface custom_font;
ArrayList<Categories> mData;
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
int BookID;
public void add(Categories s,int position) {
position = position == -1 ? getItemCount() : position;
mData.add(position,s);
notifyItemInserted(position);
}
public void remove(int position){
if (position < getItemCount() ) {
mData.remove(position);
notifyItemRemoved(position);
}
}
public DrawerItemCustomAdapterForAllBooks(Context context, ArrayList<Categories> Categories2, int BookID) {
this.mData = Categories2;
this.context = context;
this.BookID = BookID;
custom_font = Typeface.createFromAsset(context.getAssets(), "fonts/HelveticaNeueLTArabic-Light.ttf");
}
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(context).inflate(R.layout.listview_item_row, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(SimpleViewHolder holder, final int position) {
if (holder != null) {
final Categories currentItem = getItem(holder.getAdapterPosition());
SimpleViewHolder genericViewHolder = (SimpleViewHolder) holder;
genericViewHolder.position = holder.getAdapterPosition();
genericViewHolder.CategoryName.setText(currentItem.getName());
genericViewHolder.CategoryName.setTypeface(custom_font);
genericViewHolder.CategoryName.setTag(holder.getAdapterPosition());
genericViewHolder.itemView.setTag(holder.getAdapterPosition());
if (currentItem.getBookID() == 1) {
genericViewHolder.CategoryName.setTextColor(context.getResources().getColor(R.color.nokhba_white));
genericViewHolder.itemView.setBackgroundColor(context.getResources().getColor(R.color.nokhba_darkrose));
Picasso.with(context).load(R.drawable.list_icon_e02)
.error(R.drawable.no_internet)
.tag(context)
.placeholder(R.drawable.no_spic)
.into(genericViewHolder.CategoryImage);
} else if (currentItem.getBookID() == 2) {
genericViewHolder.itemView.setBackgroundColor(context.getResources().getColor(R.color.nokhba_openrose));
genericViewHolder.CategoryName.setTextColor(context.getResources().getColor(R.color.nokhba_darkrose));
Picasso.with(context).load(R.drawable.list_icon_08)
.error(R.drawable.no_internet)
.tag(context)
.placeholder(R.drawable.no_spic)
.into(genericViewHolder.CategoryImage);
} else if (currentItem.getBookID() == 3) {
genericViewHolder.CategoryName.setTextColor(context.getResources().getColor(R.color.nokhba_darkrose));
genericViewHolder.itemView.setBackgroundColor(context.getResources().getColor(R.color.nokhba_white));
Picasso.with(context).load(R.drawable.list_icon_08)
.error(R.drawable.no_internet)
.tag(context)
.placeholder(R.drawable.no_spic)
.into(genericViewHolder.CategoryImage);
}
}
}
#Override
public int getItemCount() {
return mData.size()-2;
}
public Categories getItem(int position) {
return mData.get(position-1);
}
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
protected TextView CategoryName;
protected ImageView CategoryImage;
protected View itemView;
int position = -1;
public SimpleViewHolder(View itemView) {
super(itemView);
this.CategoryName = (TextView) itemView.findViewById(R.id.CategoryName);
this.CategoryImage = (ImageView) itemView.findViewById(R.id.CategoryImage);
// CategoryName.setTypeface(custom_font);
this.itemView = itemView;
getAdapterPosition();
this.CategoryName = (TextView) itemView.findViewById(R.id.CategoryName);
this.CategoryImage = (ImageView) itemView.findViewById(R.id.CategoryImage); }
}
}

With the library SectionedRecyclerViewAdapter you can group your items in sections and add a header to each section without worrying about the "position" of the headers:
class MySection extends StatelessSection {
String title;
List<Categories> list;
public MySection(String title, List<Categories> list) {
// call constructor with layout resources for this Section header, footer and items
super(R.layout.section_header, R.layout.section_item);
this.title = title;
this.list = list;
}
#Override
public int getContentItemsTotal() {
return list.size(); // number of items of this section
}
#Override
public RecyclerView.ViewHolder getItemViewHolder(View view) {
// return a custom instance of ViewHolder for the items of this section
return new MyItemViewHolder(view);
}
#Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
MyItemViewHolder itemHolder = (MyItemViewHolder) holder;
// bind your view here
itemHolder.tvItem.setText(list.get(position).getName());
}
#Override
public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
return new SimpleHeaderViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
MyHeaderViewHolder headerHolder = (MyHeaderViewHolder) holder;
// bind your header view here
headerHolder.tvItem.setText(title);
}
}
Then you set up the RecyclerView with your Sections:
// Create an instance of SectionedRecyclerViewAdapter
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();
// Create your sections with a sub list of data from mData
MySection data1Section = new MySection("First 10 elements start", categories1List);
MySection data2Section = new MySection("Elements from 10 to 20 start", categories2List);
MySection data3Section = new MySection("Elements from 20 to 30 start", categories3List);
// Add your Sections to the adapter
sectionAdapter.addSection(data1Section);
sectionAdapter.addSection(data2Section);
sectionAdapter.addSection(data3Section);
// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);

Related

How can i modify getItemViewType() with adapter input as a string and cursor?

I have created a recycler view and want to put two lists in it.
The first list is just a string that gets changed into fonts, which I have implemented in the onBindView method.
The second list is the cursor which includes the favorite fonts of the users.
I followed this answer on SO but I don't have any idea how I'm going to modify the getItemViewType() method so that I can get to know which list type is currently calling for view.
My adapter code
here data is the class that contains the list of fonts
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int VIEW_TYPE_TEXTVIEW = 0;
private final int VIEW_TYPE_ITEM_1 = 1;
private int total_no_of_row;
private Context context;
private String str;
private Cursor cursor;
private final LayoutInflater inflater;
public MyAdapter(Context context, int total_no_of_row, String str , Cursor cursor) {
this.context = context;
this.total_no_of_row = total_no_of_row;
this.str = str;
this.cursor = cursor;
inflater = LayoutInflater.from(context);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if(viewType == VIEW_TYPE_TEXTVIEW) {
View view = inflater.inflate(R.layout.row_layout, parent, false);
return new Item1Holder(view);
}
else if (viewType == VIEW_TYPE_ITEM_1){
View view = inflater.inflate(R.layout.row_layout, parent, false);
return new Item2Holder(view);
}
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
if(holder instanceof Item1Holder){
data d = new data();
cursor.moveToPosition(position);
Log.d("this2",cursor.getInt(1)+"");
String temp = d.Convert(str, cursor.getInt(1));
((Item1Holder)holder).textView.setText(temp);
((Item1Holder)holder).rowNumber.setText("⚫");
((Item1Holder)holder).fav.setImageResource(R.drawable.ic_baseline_favorite_24);
}else if(holder instanceof Item2Holder){
data d = new data();
String temp = d.Convert(str, position);
((Item2Holder)holder).textView.setText(temp);
((Item2Holder)holder).rowNumber.setText((position + 1) + ".");
if (util.COPY) {
if (position == util.CURRENT_POSITION) {
((Item2Holder)holder).imageView.setBackgroundResource(R.drawable.background_when_row_clicked);
} else {
((Item2Holder)holder).imageView.setBackgroundResource(R.drawable.background_when_row_clicked_two);
}
}
}
}
#Override
public int getItemCount() {
return total_no_of_row + cursor.getCount();
}
class Item1Holder extends RecyclerView.ViewHolder {
TextView textView;
ImageView imageView , fav;
TextView rowNumber;
public Item1Holder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_body);
imageView = itemView.findViewById(R.id.copy_png);
rowNumber = itemView.findViewById(R.id.row_number);
fav = itemView.findViewById(R.id.fav);
}
}
class Item2Holder extends RecyclerView.ViewHolder {
TextView textView;
ImageView imageView , fav;
TextView rowNumber;
public Item2Holder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_body);
imageView = itemView.findViewById(R.id.copy_png);
rowNumber = itemView.findViewById(R.id.row_number);
fav = itemView.findViewById(R.id.fav);
}
}
}
in main activity
here temp is the string that users want to convert into the fonts
Cursor cursor = show();
myAdapter = new MyAdapter(this , 500 , temp , cursor);
recyclerView.setAdapter(myAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
I'm not a professional android developer I'm still learning the stuff. so sorry if my code is too bad to understand
You are passing null in the onCreateViewHolder() method, and not specified position in getItemViewType() method. All you have to do is, update your code. do not pass the null value in the onCreateViewHolder method. Below code, I've tried, and works perfectly. Happy coding...
private static final int CATEGORY = 1;
private static final int NAME = 2;
private Collection<CategorizedName> data;
#Override
public int getItemViewType(int position) {
if (items.get(position) instanceof Category) {
return CATEGORY;
} else if (items.get(position) instanceof Name) {
return NAME;
}
throw new RuntimeException('error');
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
RecyclerView.ViewHolder viewHolder;
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
switch (viewType) {
case CATEGORY:
View categoryView = inflater.inflate(R.layout.viewholder_category, viewGroup,
false);
viewHolder = new CategoryViewHolder(categoryView);
break;
case NAME:
View nameView = inflater.inflate(R.layout.viewholder_name, viewGroup, false);
viewHolder = new NameViewHolder(nameView);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
switch (viewHolder.getItemViewType()) {
case USER:
CategoryViewHolder categoryViewHolder = (CategoryViewHolder) viewHolder;
bindCategoryViewHolder(categoryViewHolder, position);
break;
case IMAGE:
NameViewHolder nameViewHolder = (NameViewHolder) viewHolder;
bindNameViewHolder(nameViewHolder, position);
break;
}
}
Replace your getItemViewType() with this
#Override
public int getItemViewType(int position){
if(position < total_no_of_row){
return VIEW_TYPE_TEXTVIEW;
}
if(position - total_no_of_row < cursor.getCount()){
return VIEW_TYPE_ITEM_1;
}
return -1;
}
you can also refer to my answer this

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.

Recycler View linear layout manager returning null

I have a recycler view which contains multiple items and each item in the recycler view contains a horizontal recycler view.The problem I am encountering is that the layout manager is null.
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
This is my code so far.I have checked that the data I am receiving is intact.
RecipeAdapter ( The main adapter )
public class RecipeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<Object> items;
private final int RECIPE = 0, JOKE = 1;
public RecipeAdapter(Context context) {
this.context = context;
this.items = new ArrayList<>();
}
public void setItems(List<Object> items) {
this.items = items;
}
public void add(Object object) {
items.add(object);
notifyItemInserted(items.size());
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder;
final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case RECIPE:
View recipe = inflater.inflate(R.layout.item_recipe, parent, false);
viewHolder = new ViewHolder_Recipe(recipe);
break;
case JOKE:
View joke = inflater.inflate(R.layout.item_joke, parent, false);
viewHolder = new ViewHolder_Joke(joke);
break;
default:
View recipe_default = inflater.inflate(R.layout.item_recipe, parent, false);
viewHolder = new ViewHolder_Recipe(recipe_default);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case RECIPE:
ViewHolder_Recipe viewHolderRecipe = (ViewHolder_Recipe) holder;
configureRecipeHolder(viewHolderRecipe, position);
break;
case JOKE:
ViewHolder_Joke viewHolderJoke = (ViewHolder_Joke) holder;
configureJokeHolder(viewHolderJoke, position);
break;
default:
ViewHolder_Recipe viewHolder_recipe_default = (ViewHolder_Recipe) holder;
configureRecipeHolder(viewHolder_recipe_default, position);
break;
}
}
private void configureJokeHolder(ViewHolder_Joke viewHolderJoke, int position) {
}
private void configureRecipeHolder(ViewHolder_Recipe viewHolderRecipe, int position) {
RecipeDetailed recipe = (RecipeDetailed) items.get(position);
Glide.with(context)
.load(recipe.getImage())
.into(viewHolderRecipe.getRecipe_image());
viewHolderRecipe.getRecipe_name().setText(recipe.getTitle());
viewHolderRecipe.getRecipe_prep().setText(recipe.getReadyInMinutes());
viewHolderRecipe.getRecipe_serves().setText(recipe.getServings());
viewHolderRecipe.getIngredientAdapter().setIngredients(recipe.getExtendedIngredients());
}
#Override
public int getItemViewType(int position) {
if (items.get(position) instanceof RecipeDetailed) {
return RECIPE;
} else if (items.get(position) instanceof Joke) {
return JOKE;
}
return super.getItemViewType(position);
}
#Override
public int getItemCount() {
return items.size();
}
}
The ViewHolder for that Adapter -- ViewHolder_Recipe
public class ViewHolder_Recipe extends RecyclerView.ViewHolder {
private CircularImageView recipe_image;
private TextView recipe_name;
private TextView recipe_prep;
private TextView recipe_serves;
private RecyclerView recyclerView;
private RecipeIngredientAdapter ingredientAdapter;
public ViewHolder_Recipe(View itemView) {
super(itemView);
recipe_image = (CircularImageView) itemView.findViewById(R.id.recipe_image);
recipe_name = (TextView) itemView.findViewById(R.id.recipe_name);
recipe_prep = (TextView) itemView.findViewById(R.id.recipe_prep);
recipe_serves = (TextView) itemView.findViewById(R.id.recipe_serves);
recyclerView = (RecyclerView) itemView.findViewById(R.id.recyclerView);
ingredientAdapter = new RecipeIngredientAdapter(itemView.getContext());
recyclerView.setLayoutManager(new LinearLayoutManager(itemView.getContext()
, LinearLayoutManager.HORIZONTAL, false));
recyclerView.setAdapter(ingredientAdapter);
}
public RecipeIngredientAdapter getIngredientAdapter() {
return ingredientAdapter;
}
public CircularImageView getRecipe_image() {
return recipe_image;
}
public TextView getRecipe_name() {
return recipe_name;
}
public TextView getRecipe_prep() {
return recipe_prep;
}
public TextView getRecipe_serves() {
return recipe_serves;
}
public RecyclerView getRecyclerView() {
return recyclerView;
}
}
The child adapter -- RecipeIngredientAdapter
public class RecipeIngredientAdapter extends RecyclerView.Adapter<ViewHolderRecipeIngredient> {
private Context context;
private ArrayList<Ingredient> ingredients;
public RecipeIngredientAdapter(Context context) {
this.context = context;
}
public void setIngredients(ArrayList<Ingredient> ingredients) {
this.ingredients = ingredients;
}
#Override
public ViewHolderRecipeIngredient onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.item_recipe_ingredients, parent, false);
return new ViewHolderRecipeIngredient(view);
}
#Override
public void onBindViewHolder(ViewHolderRecipeIngredient holder, int position) {
final Ingredient ingredient = ingredients.get(position);
Glide.with(context)
.load(ingredient.getImage())
.into(holder.getIngredient_image());
}
#Override
public int getItemCount() {
return 0;
}
}
The viewholder for that is a simple viewholder which contains an image.
I have seen posts online which seem to do the exact same thing and get it working,what exactly am i missing here?
From the error, it sounds like the RecyclerView is null, not the LayoutManager. Make sure you are using the proper id from the layout. are you sure the proper layout id of the RecyclerView is R.id.recyclerView?

overwriting array list's items after calling notifyDataSetChanged() [java] [android]

I have a class like this:
public class ComponentMain implements Serializable {
private ArrayList<Integer> componentsIDs;
private int availableCount;
private String component_name;
private String component_desc;
and I'm using RecycleView.
In the activity the code looks like this
private List<ComponentMain> componentMains = new ArrayList<>();
recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
mAdapter = new ComponentAdapter(getActivity(),componentMains);
recyclerView.setAdapter(mAdapter);
And I'm adding element to componentMains.
private List<Component> componentList = new ArrayList<>();
//adding data to componentList here.
String tmp = componentList.get(0).getComponent_name() ;
ArrayList<Integer> oneComponent = new ArrayList<>();
oneComponent.add(componentList.get(0).getComponent_id_Integer());
int i;
for (i = 1; i< componentList.size(); ++i) {
if(componentList.get(i).getComponent_name().equals(tmp)) {
oneComponent.add(componentList.get(i).getComponent_id_Integer());
tmp = componentList.get(i).getComponent_name();
} else {
//ArrayList<Integer> componentsIDs, String component_name, String component_desc
//
ComponentMain mainComp = new ComponentMain(oneComponent,componentList.get(i-1).getComponent_name(),componentList.get(i-1).getComponent_desc());
componentMains.add(mainComp);
oneComponent.clear();
oneComponent.add(componentList.get(i).getComponent_id_Integer());
tmp = componentList.get(i).getComponent_name();
}
}
ComponentMain mainComp = new ComponentMain(oneComponent,componentList.get(i-1).getComponent_name(),componentList.get(i-1).getComponent_desc());
componentMains.add(mainComp);
}
I'm grouping components by name and storing ArrayList of IDs for each name;
At the end I'm calling
mAdapter.notifyDataSetChanged();
The problem is after I call notifyDataSetChanged() , for every object in componentMains list, the value of componentsIDs list is same as the value of the last one in componentsMains list .
Here's the code od ComponentAdapter class
public class ComponentAdapter extends RecyclerView.Adapter<ComponentAdapter.MyViewHolder> {
private List<ComponentMain> componentList;
private Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name,description,availableCount;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
description = (TextView) view.findViewById(R.id.description);
available = (TextView) view.findViewById(R.id.available);
}
}
public ComponentAdapter(Context context, List<ComponentMain> componentList) {
this.context = context;
this.componentList = componentList;
}
#Override
public ComponentAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.component_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ComponentAdapter.MyViewHolder holder, int position) {
ComponentMain component = componentList.get(position);
holder.name.setText(component.getComponent_name());
holder.description.setText(component.getComponent_desc());
holder.available.setText(component.getAvailableCount()+"");
}
#Override
public int getItemCount() {
return componentList.size();
}
}

Categories