recyclerview adapter anonymous arraylist error - android

I have the 2 errors , can you help me to fix them ?
this error in main activity
This is the code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view);
//first recycler
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(
new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false));
OkHttpHandler handler = new OkHttpHandler( this, new OkHttpHandler.MyInterface() {
#Override
public void myMethod(ArrayList result) {
mAdapter = new MyAdapter(result,this);
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
// GridViewAdapter adapter = new GridViewAdapter(getApplicationContext(), R.layout.grid_item_layout, result);
// adapter.notifyDataSetChanged();
// mGridView.setAdapter(adapter);
}
});
and second error here in my adapter
// viewHolder.txtHeader.setText(...)
final Listitem item;
// final String name = mDataset.get(position);
item = mDataset.get(position);
viewHolder.txtHeader.setText(mDataset.get(position));
this is the full code
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Listitem> mDataset;
Context mContext;
public class ImageViewHolder extends RecyclerView.ViewHolder {
//ImageView mImage;
public TextView txtHeader;
public TextView txtFooter;
public ImageViewHolder(View itemView) {
super (itemView);
txtHeader = (TextView) itemView.findViewById(R.id.firstLine);
txtFooter = (TextView) itemView.findViewById(R.id.secondLine);
}
}
public void add(int position, Listitem item) { //changed from string to listitem
mDataset.add(position, item);
notifyItemInserted(position);
}
public void remove(String item) {
int position = mDataset.indexOf(item);
mDataset.remove(position);
notifyItemRemoved(position);
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(ArrayList<Listitem> myDataset, Context context) {
mDataset = myDataset;
mContext = context;
}
// Create new views (invoked by the layout manager)
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false);
// set the view's size, margins, paddings and layout parameters
ImageViewHolder vh = new ImageViewHolder(v);
return vh;
}
private static final int TYPE_IMAGE = 1;
private static final int TYPE_GROUP = 2;
#Override
public int getItemViewType(int position) {
// here your custom logic to choose the view type
return position;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder TextViewHolder, int position) {
ImageViewHolder viewHolder = (ImageViewHolder) TextViewHolder;
// viewHolder.txtHeader.setText(...)
final Listitem item;
// final String name = mDataset.get(position);
item = mDataset.get(position);
viewHolder.txtHeader.setText(mDataset.get(position));
/* viewHolder.txtFooter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
remove(item);
}
});*/
// viewHolder.txtFooter.setText("Footer: " + mDataset.get(position));
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
}
listitem
public class Listitem implements Parcelable {
String id;
//String name;
String url;
Listitem (Parcel in){
this.id = in.readString();
// this.name = in.readString();
this.url = in.readString();
}
Listitem( String name,String url) {
this.id = id;
this.url = url;
}
#Override
public int describeContents() {
return 0;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.id);
// dest.writeString(this.name);
dest.writeString(this.url);
}
public static final Parcelable.Creator<Listitem> CREATOR = new Parcelable.Creator<Listitem>() {
public Listitem createFromParcel(Parcel in) {
return new Listitem(in);
}
public Listitem[] newArray(int size) {
return new Listitem[size];
}
};
}

For the first error:
You need to pass a Context in the adapter constructor.
Actually this inside myMethod(ArrayList result) refers to OkHttpHandler.MyInterface not a Context.
To solve this, change mAdapter = new MyAdapter(result,this);
to mAdapter = new MyAdapter(result,YourActivityName.this);
For the second error:
mDataset.get(position) is returning a Listitem object, while you need a CharSequence (or String) object as parameter with setText() method.
You should do
viewHolder.txtHeader.setText(mDataset.get(position).getUrl());
or
viewHolder.txtHeader.setText(mDataset.get(position).getId());

Related

how displaying server information in Recyclerview?

I want to write a program to retrieve information from the server and display it in the Recycler View,But I have two problems.
When I add data to the table it will be added to the Recycler View list But when I delete, the list doesn't change.
2.Photos of each section cannot be loaded.
home.java
public class Home extends Fragment {
public Home() {
// Required empty public constructor
}
SwipeRefreshLayout srl;
RecyclerView rv;
FloatingActionButton add;
ArrayList<Post> al;
PostAdapter pa;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
srl = getActivity().findViewById(R.id.srl);
rv = getActivity().findViewById(R.id.rv);
// add = getActivity().findViewById(R.id.add);
AndroidNetworking.initialize(getContext());
al = new ArrayList<>();
pa = new PostAdapter(getContext(),al);
rv.setHasFixedSize(true);
rv.setItemAnimator(new DefaultItemAnimator());
rv.setLayoutManager(new LinearLayoutManager(getContext()));
rv.setAdapter(pa);
update();
srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
update();
}
});
}
private void update(){
String id = al.size() == 0 ? "0" : al.get(0).getId();
AndroidNetworking.post(Urls.host+Urls.post)
.addBodyParameter("id",id)
.build()
.getAsObjectList(Post.class, new ParsedRequestListener<List<Post>>() {
#Override
public void onResponse(List<Post> response) {
srl.setRefreshing(false);
for (Post p : response){
al.add(0,p);
pa.notifyDataSetChanged();
}
}
#Override
public void onError(ANError anError) {
srl.setRefreshing(false);
}
});
}
}
postadapter.java
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
Context context;
ArrayList<Post> al;
LayoutInflater inflater;
public PostAdapter(Context ctx,ArrayList<Post> arl){
context = ctx;
al = arl;
inflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.rv_item,null,false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(lp);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Post s = al.get(position);
holder.title.setText(s.getTitle());
holder.text.setText(s.getText());
holder.date.setText(s.getDate());
holder.image.setImageUrl(Urls.host+s.getImage());
holder.image.setDefaultImageResId(R.drawable.material);
holder.image.setErrorImageResId(R.drawable.material);
}
#Override
public int getItemCount() {
return al.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
ANImageView image;
AppCompatTextView title, text, date;
AppCompatImageView share;
public ViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
title = itemView.findViewById(R.id.title);
text = itemView.findViewById(R.id.text);
date = itemView.findViewById(R.id.date);
}
}
}
post.java
public class Post {
String title,text, date,id;
int imageUrl;
public Post(int imageUrl, String title, String text, String time, String id) {
this.imageUrl = imageUrl;
this.title = title;
this.text = text;
this.date = time;
this.id = id;
}
public int getImage() {
return imageUrl;
}
public void setImage(int imageUrl) {
this.imageUrl = imageUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Try this
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
Context context;
ArrayList<Post> al;
ArrayList<Post> newDataList;
LayoutInflater inflater;
public PostAdapter(Context ctx,ArrayList<Post> arl){
context = ctx;
al = arl;
inflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.rv_item,null,false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(lp);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Post s = al.get(position);
holder.title.setText(s.getTitle());
holder.text.setText(s.getText());
holder.date.setText(s.getDate());
holder.image.setImageUrl(Urls.host+s.getImage());
holder.image.setDefaultImageResId(R.drawable.material);
holder.image.setErrorImageResId(R.drawable.material);
}
#Override
public int getItemCount() {
return al.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
ANImageView image;
AppCompatTextView title, text, date;
AppCompatImageView share;
public ViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
title = itemView.findViewById(R.id.title);
text = itemView.findViewById(R.id.text);
date = itemView.findViewById(R.id.date);
}
public ArrayList<Post> getDataSet() {
return al;
}
public void refresh(ArrayList<Post> list) {
newDataList = new ArrayList<>();
newDataList.addAll(list);
al.clear();
al.addAll(newDataList);
notifyDataSetChanged();
}
}
Now at time when you wants to add or delete try getting adapter.getDataSet()
and update list with adapter.refresh(yourList)

Child item not showing up in expandable recycler view

This is my adapter class
public class GenreAdapter extends ExpandableRecyclerViewAdapter<GenreViewHolder, ArtistViewHolder> {
Context context ;
LayoutInflater inflater ;
public GenreAdapter(List<? extends ExpandableGroup> groups,Context context) {
super(groups);
this.context = context ;
inflater = LayoutInflater.from(context);
}
#Override
public GenreViewHolder onCreateGroupViewHolder(ViewGroup parent, int viewType) {
//LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.list_item_genre, parent, false);
return new GenreViewHolder(view);
}
#Override
public ArtistViewHolder onCreateChildViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_item_artist, parent, false);
return new ArtistViewHolder(view);
}
#Override
public void onBindChildViewHolder(ArtistViewHolder holder, int flatPosition, ExpandableGroup group,
int childIndex) {
final Artist artist =(Artist) group.getItems().get(childIndex);
holder.setArtistName(artist.getName());
}
#Override
public void onBindGroupViewHolder(GenreViewHolder holder, int flatPosition,
ExpandableGroup group) {
holder.setGenreTitle(group);
}
}
This is my model class
package com.nmn.expandablerecycler.utils;
import android.os.Parcel;
import android.os.Parcelable;
import com.thoughtbot.expandablerecyclerview.models.ExpandableGroup;
import java.util.List;
public class Artist implements Parcelable {
private String name;
private boolean isFavorite;
public Artist(String name, boolean isFavorite) {
this.name = name;
this.isFavorite = isFavorite;
}
protected Artist(Parcel in) {
name = in.readString();
}
public String getName() {
return name;
}
/* public String getTitle()
{
return title ;
}*/
public boolean isFavorite() {
return isFavorite;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Artist)) return false;
Artist artist = (Artist) o;
if (isFavorite() != artist.isFavorite()) return false;
return getName() != null ? getName().equals(artist.getName()) : artist.getName() == null;
}
#Override
public int hashCode() {
int result = getName() != null ? getName().hashCode() : 0;
result = 31 * result + (isFavorite() ? 1 : 0);
return result;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<Artist> CREATOR = new Creator<Artist>() {
#Override
public Artist createFromParcel(Parcel in) {
return new Artist(in);
}
#Override
public Artist[] newArray(int size) {
return new Artist[size];
}
};
}
public class Genre extends ExpandableGroup<Artist> {
public Genre(String title, List<Artist> items) {
super(title, items);
}
}
>This are my viewholder classes
public class ArtistViewHolder extends ChildViewHolder {
private TextView artistName;
public ArtistViewHolder(View itemView) {
super(itemView);
artistName = (TextView) itemView.findViewById(R.id.artist_name);
}
public void onBind(Artist artist) {
artistName.setText(artist.getName());
}
public void setArtistName (String name )
{
}
}
public class GenreViewHolder extends GroupViewHolder {
private TextView genreTitle;
public GenreViewHolder(View itemView) {
super(itemView);
genreTitle =(TextView) itemView.findViewById(R.id.genre_title);
}
public void setGenreTitle(ExpandableGroup group) {
genreTitle.setText(group.getTitle());
}
}
>this is the main activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Artist>artists = new ArrayList<>();
for (int i = 0 ; i<6 ;i++)
{
artists.add(new Artist("naman",true));
}
ArrayList<Genre> genres = new ArrayList<>();
for (int i = 0 ; i<6 ;i++)
{
genres.add(new Genre("Sufi",artists));
}
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
//instantiate your adapter with the list of genres
GenreAdapter adapter = new GenreAdapter(genres,this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
}
The text on the artist(child) name is not shown up . Althiugh the parent (genre text ) expands and collapses as well .Let me know how to
show the text of child (artist) item in this expandable recyclerview
Dude this might sound silly, but your setArtistName method is empty. paste this code artistName.setText(artist.getName());
The library documentation has error
public void onBind(Artist artist) {
artistName.setText(artist.getName());
}
public void setArtistName (String name )
{
}
In this snippet just change the name of method from onBind to setArtistName and remove the empty method you created.
I was also implementing com.thoughtbot.expandablerecyclerview. What I did in the same scenario was, in the custom class that is extending ExpandableGroup, I override getItems() and getItemCount() methods and provided the values which I wanted as "child"-expanded state.

Horizontal and vertical recyclerview parsing json data in Android

See sanpshot here
jObject = new JSONObject(result);
JSONObject resultObj = jObject.getJSONObject("result");
for(int i = 0; i < firstproducts.size(); i++) {
try {
title = firstproducts.get(i).getString("category");
categoryIcon = firstproducts.get(i).getString("icon_img");
Log.e("For I","Value : "+title);
for(int j = 0; j < secondproducts.size(); j++) {
if(title.equalsIgnoreCase(secondproducts.get(j).getString("category"))){
categoryIcon = secondproducts.get(j).getJSONObject("info").getString("img");
JSONArray products=null;
products = firstproducts.get(j).gptJSONArray("Products"); if(products!=null) {
for (int k = 0; k < products.length(); k++) {
JSONObject jsonObj = products.getJSONObject(k);
content = jsonObj.getString("description");
points = jsonObj.getString("points");
imageUrl = jsonObj.getString("image");
secondarraylist.add(new ChildModel(content,points,rating,imageUrl));
}
}
mainarraylist.add(new MainModel(title,categoryIcon,secondarraylist));
finally i set this above main arraylist to recyclerview adapter
------------------------------- ---------
Mian Model class as below -child model inside 3 string values will be there.
public class MainModel {
String title;
String categoryIcon;
private List<ChildModel> ChildItems;
public MainModel() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategoryIcon() {
return categoryIcon;
}
public void setCategoryIcon(String categoryIcon) {
this.categoryIcon = categoryIcon;
}
public List<ChildModel> getChildItems() {
return ChildItems;
}
public void setItems(List<ChildModel> ChildItems) {
this.ChildItems = ChildItems;
}
}
---------------------------------------
Main adapter
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ProductViewHolder> {
private final Context mContext;
List<MainModel> maindata;
public MainAdapter(Context mContext, List<MainModel> ProductList) {
this.mContext = mContext;
this.maindata=ProductList;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.product_list_store, parent, false);
return new ProductViewHolder(view);
}
public class ProductViewHolder extends RecyclerView.ViewHolder {
public final TextView title;
public final ImageView categoryIcon;
public final ImageView leftArrow;
public final ImageView rightArrow;
public final View categoryDiver;
private ChildAdapter horizontalAdapter;
private RecyclerView horizontalList;
private LinearLayoutManager llm;
public ProductViewHolder(View view) {
super(view);
Context context = itemView.getContext();
title = (TextView) view.findViewById(R.id.product_textForHeader);
categoryIcon = (ImageView) view.findViewById(R.id.product_Iconimageview);
leftArrow = (ImageView)view.findViewById(R.id.product_leftside_arrow);
rightArrow = (ImageView)view.findViewById(R.id.product_rightside_arrow);
categoryDiver = view.findViewById(R.id.product_Divider_view);
horizontalList = (RecyclerView) itemView.findViewById(R.id.horizontal_layout);
llm = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
horizontalList.setLayoutManager(llm);
horizontalAdapter = new ChildAdapter(context);
horizontalList.setAdapter(horizontalAdapter);
}
}
#Override
public void onBindViewHolder(final ProductViewHolder holder, int position) {
holder.title.setText(maindata.get(position).getTitle());
holder.horizontalAdapter.setData(maindata.get(position).getStoreItems()); // List of Strings
holder.horizontalAdapter.setRowIndex(position);
holder.leftArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("left");
if (holder.llm.findFirstCompletelyVisibleItemPosition() > 0){
holder.horizontalList.smoothScrollToPosition(holder.llm.findFirstVisibleItemPosition() - 1);
}
}
});
holder.rightArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("right");
holder.horizontalList.smoothScrollToPosition(holder.llm.findFirstVisibleItemPosition() + 1);
}
});
if(position == maindata.size()-1)
holder.categoryDiver.setVisibility(View.GONE);
}
#Override
public int getItemCount() {
//return 0;
return maindata.size();
}
}
-------------------------------------------
ChildAdapter
public class ChildAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
private List<ChildModel> childdata;
private ImageLoader imageLoader;
private int mRowIndex = -1;
public ChildAdapter(Context context) {
this.context = context;
}
public void setData(List<ChildModel> data) {
if (childdata != data) {
childdata = data;
notifyDataSetChanged();
}
}
publindex;
}
private class ItemViewHolder extends RecyclerView.ViewHolder {
public final TextView content;
public final TextView rating;
public final TextView points;
public final NetworkImageView img_item;
public final ImageView img_rating;
public ItemViewHolder(View view) {
super(view);
content = (TextView) view.findViewById(R.id.category_item_title);
rating = (TextView) view.findViewById(R.id.text_rating);
points = (TextView) view.findViewById(R.id.category_points);
img_item = (NetworkImageView) view.findViewById(R.id.category_item_imageView);
img_rating= (ImageView) view.findViewById(R.id.img_rating);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
View itemView = LayoutInflater.from(context).inflate(R.layout.store_category_item, parent, false);
ItemViewHolder holder = new ItemViewHolder(itemView);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewholder, int position) {
ItemViewHolder holder=(ItemViewHolder)viewholder;
holder.content.setText(childdata.get(position).getContent());
holder.points.setText(childdata.get(position).getPoints());
holder.rating.setText(childdata.get(position).getRating());
holder.itemView.setTag(position);
}
#Override
public int getItemCount() {
return childdata.size();
}
}
I am doing a project with horizontal and vertical recyclerview same like a play store. I have done all the designs like 2 adapters and 2 model class.
The problem is I parsed json and set all the data to 2 array list so all the data come to horizontal adapters. how to set horizontal values from arraylist according to below heading thats dynamic.
This is my API: bikes, cars, trucks; I need to set this data vertical recyclerview heading and inside products array that is horizontal recyclerview:
I can tell you the approach-->Get all child json in the main array-->then in each of these json object get the products jsonobject and set them accordingly

Sticky Header RecyclerView with multiple ArrayLists

I am implementing sticky header with RecyclerView. I have three sections (i.e 3 sticky headers) and they are working fine.Now I have taken three arraylists inside each section, I have initialized these list in my adapter and I am trying to get data of these lists on basis of header id inside onBindViewHolder. But it is not giving me the full list,just one string from each list (i.e under first section--data on first position of mylist,,,under second section-- data on second position of mylist1 ---under third section-- data on third position of mylist2)
Please Help !!
Code in Context:
StickyTestAdapter
public class StickyTestAdapter extends RecyclerView.Adapter<StickyTestAdapter.ViewHolder> implements
StickyHeaderAdapter<StickyTestAdapter.HeaderHolder> {
private Context mContext;
private ArrayList<String> mylist;
private ArrayList<String> mylist1;
private ArrayList<String> mylist2;
private static int countposition;
private String HEADER_FIRIST="HEADER_FIRIST";
private String HEADER_SECOND="HEADER_SECOND";
private String HEADER_THIRD="HEADER_THIRD";
public StickyTestAdapter(Context context) {
prepareData();
prepareData1();
prepareData2();
this.mContext=context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.item_test, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
long rowType= getHeaderId(position);
Log.e("getHeaderId----",""+rowType);
if (rowType==0){
if(!mylist.equals(""))
{
Log.e("list_data----", "" + mylist.get(position));
viewHolder.item.setText(mylist.get(position));
}
else
{
Log.e("Error--0--", "" + "error");
}
} else if (rowType==1){
if(!mylist1.equals(""))
{
Log.e("list_data1----", "" + mylist1.get(position));
viewHolder.item.setText(mylist1.get(position));
}
else
{
Log.e("Error---1-", "" + "error");
}
} else if (rowType==2){
if(!mylist2.equals(""))
{
Log.e("list_data2----", "" + mylist2.get(position));
viewHolder.item.setText(mylist2.get(position));
}
else
{
Log.e("Error----2", "" + "error");
}
}
}
#Override
public int getItemCount() {
if (getHeaderId(countposition)==0){
Log.e("mylist",""+mylist.size());
return mylist.size();
}else if (getHeaderId(countposition)==1){
Log.e("mylist1",""+mylist1.size());
return mylist1.size();
}else if (getHeaderId(countposition)==2){
Log.e("mylist2",""+mylist2.size());
return mylist2.size();
}
return 0;
}
#Override
public long getHeaderId(int pos) {
return pos;
}
#Override
public HeaderHolder onCreateHeaderViewHolder(ViewGroup parent) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.header_test, parent, false);
return new HeaderHolder(view);
}
#Override
public void onBindHeaderViewHolder(HeaderHolder viewholder, int count) {
countposition=count;
if (getItemViewType(count)==0){
viewholder.headertext.setText(HEADER_FIRIST);
}else if (getItemViewType(count)==1){
viewholder.headertext.setText(HEADER_SECOND);
}else if (getItemViewType(count)==2){
viewholder.headertext.setText(HEADER_THIRD);
}
}
static class ViewHolder extends RecyclerView.ViewHolder {
public TextView item;
public ViewHolder(View itemView) {
super(itemView);
item = (TextView)itemView.findViewById(R.id.text_item);
}
}
static class HeaderHolder extends RecyclerView.ViewHolder {
public TextView headertext;
public HeaderHolder(View itemView) {
super(itemView);
headertext = (TextView)itemView.findViewById(R.id.header_text);
}
}
#Override
public int getItemViewType(int position) {
return position;
}
public void prepareData()
{
mylist=new ArrayList<>();
mylist.add("rajendra");
mylist.add("rani");
mylist.add("rahul");
}
public void prepareData1()
{
mylist1=new ArrayList<>();
mylist1.add("ravi");
mylist1.add("vikram");
mylist1.add("rakesh");
}
public void prepareData2()
{
mylist2=new ArrayList<>();
mylist2.add("apple");
mylist2.add("ashok");
mylist2.add("vikash");
}
}
Question is quite old. But that code looks complicated to read, personally I try to not reinvent what others did quite well by creating libraries.
GitHub is full of source that you can import. Some examples: FlexibleAdapter, FastAdapter, Epoxy and others.
I have build the first one, but you can try the others as well.
With mine, having multiple views and headers with sections is quite easy, I point here the wiki page where I define the section and how to initialize it.
Along with this feature, you have a lot more functionalities that makes your life easier.
I divide arraylist into 3 section based on alphabet like contactlist.
For that i use SectionedRecyclerViewAdapter
MainActivity.java
public class MainActivity extends AppCompactActivity {
private SectionedRecyclerViewAdapter sectionAdapter;
#Override
public View onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
sectionAdapter = new SectionedRecyclerViewAdapter();
for(char alphabet = 'a'; alphabet <= 'z';alphabet++) {
List<String> contacts = getContactsWithLetter(alphabet);
if (contacts.size() > 0) {
sectionAdapter.addSection(new ContactsSection(String.valueOf(alphabet), contacts));
}
}
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);
return view;
}
#Override
public void onResume() {
super.onResume();
if (getActivity() instanceof AppCompatActivity) {
AppCompatActivity activity = ((AppCompatActivity) getActivity());
if (activity.getSupportActionBar() != null)
activity.getSupportActionBar().setTitle(R.string.nav_example1);
}
}
private List<String> getContactsWithLetter(char letter) {
List<String> contacts = new ArrayList<>();
for (String contact : getResources().getStringArray(R.array.names_)) {
if (contact.charAt(0) == letter) {
contacts.add(contact);
}
}
return contacts;
}
private class ContactsSection extends StatelessSection {
String title;
List<String> list;
ContactsSection(String title, List<String> list) {
super(new SectionParameters.Builder(R.layout.section_ex1_item)
.headerResourceId(R.layout.section_ex1_header)
.build());
this.title = title;
this.list = list;
}
#Override
public int getContentItemsTotal() {
return list.size();
}
#Override
public RecyclerView.ViewHolder getItemViewHolder(View view) {
return new ItemViewHolder(view);
}
#Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
final ItemViewHolder itemHolder = (ItemViewHolder) holder;
String name = list.get(position);
itemHolder.tvItem.setText(name);
itemHolder.imgItem.setImageResource(name.hashCode() % 2 == 0 ? R.drawable.ic_face_black_48dp : R.drawable.ic_tag_faces_black_48dp);
itemHolder.rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), String.format("Clicked on position #%s of Section %s", sectionAdapter.getPositionInSection(itemHolder.getAdapterPosition()), title), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
return new HeaderViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
HeaderViewHolder headerHolder = (HeaderViewHolder) holder;
headerHolder.tvTitle.setText(title);
}
}
private class HeaderViewHolder extends RecyclerView.ViewHolder {
private final TextView tvTitle;
HeaderViewHolder(View view) {
super(view);
tvTitle = (TextView) view.findViewById(R.id.tvTitle);
}
}
private class ItemViewHolder extends RecyclerView.ViewHolder {
private final View rootView;
private final ImageView imgItem;
private final TextView tvItem;
ItemViewHolder(View view) {
super(view);
rootView = view;
imgItem = (ImageView) view.findViewById(R.id.imgItem);
tvItem = (TextView) view.findViewById(R.id.tvItem);
}
}
}
use structure similar to
public class MultiArray<T> {
List<ItemGroup> lists = new ArrayList<>();
public void addList(String headerText, List<T> list) {
lists.add(new ItemGroup(headerText, list));
}
public int itemCount() {
int count = 0;
for (ItemGroup group : lists) {
count += group.count();
}
return count;
}
public T getItem(int position) {
int count = 0;
for (ItemGroup group : lists) {
if (count + group.count() >= position) {
return group.item(position - count);
}
count += group.count();
}
return null;
}
public int getGroupIndex(int position) {
int count = 0;
int groupIndex = 0;
for (ItemGroup group : lists) {
if (count + group.count() >= position) {
return groupIndex;
}
count += group.count();
groupIndex++;
}
return -1;
}
public String getHeaderText(int position){
int count = 0;
for (ItemGroup group : lists) {
if (count + group.count() >= position) {
return group.headerText;
}
count += group.count();
}
return "";
}
class ItemGroup {
public final String headerText;
public final List<T> list;
public ItemGroup(String headerText, List<T> list) {
this.headerText = headerText;
this.list = list;
}
public int count() {
return list.size();
}
public T item(int position) {
return list.get(position);
}
}
}
you can optimize it for faster performance

Recycler View creating duplicate items

I am using Recycler View for creating a list of items and I am getting a duplicate items in the list. I have passed a list of 30 size into the Recycler View Adapter. The created list has 30 items but there are only 3 unique items, all other are repetition of 3 unique items. I am not able to find the bug.
public class CollectionAdapter extends RecyclerView.Adapter<CollectionAdapter.CollectionViewHolder> {
private List<CollectionDataTypeModel> mDataSet = new ArrayList<CollectionDataTypeModel>();
private Activity mActivity;
private String mType;
public CollectionAdapter(List<CollectionDataTypeModel> mDataSet, Activity activity, String type) {
this.mActivity = activity;
this.mDataSet = mDataSet;
this.mType = type;
}
#Override
public CollectionViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.collection_cardview_layout, parent, false);
CollectionViewHolder vh = new CollectionViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(final CollectionViewHolder holder, int position) {
final CollectionDataTypeModel collectionData = mDataSet.get(position);
Log.d("Colelction Adapter","name : "+collectionData.getCollectionName());
holder.titleText.setText(collectionData.getCollectionName()+"");
holder.secondaryText.setText(collectionData.getPoiCount()+" attractions");
if (mType.equalsIgnoreCase("Collection")) {
Glide.with(mActivity).load(R.drawable.aman).asBitmap().centerCrop().into(new BitmapImageViewTarget(holder.profileImage) {
#Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(mActivity.getResources(), resource);
circularBitmapDrawable.setCircular(true);
holder.profileImage.setImageDrawable(circularBitmapDrawable);
}
});
} else if (mType.equalsIgnoreCase("Destination")) {
holder.profileImageRipple.setVisibility(View.GONE);
} else if (mType.equalsIgnoreCase("Download")) {
holder.profileImageRipple.setVisibility(View.GONE);
holder.viewIcon.setImageResource(R.drawable.clear_icon);
holder.viewCount.setVisibility(View.INVISIBLE);
}
// holder.collectionImage.setImageResource(R.drawable.goldentemple);
Glide.with(mActivity).load(collectionData.getCollectionImage()).into(holder.collectionImage);
holder.likeCount.setText(Integer.toString(collectionData.getLikeCount()));
holder.viewCount.setText(Integer.toString(collectionData.getViewCount()));
holder.likeIconRipple.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
#Override
public void onComplete(RippleView rippleView) {
// if(holder.likeIcon.getDrawable()==mActivity.getDrawable(R.drawable.like_icon))
{
holder.likeIcon.setImageResource(R.drawable.like_fill_icon);
}
// else
{
// holder.likeIcon.setImageResource(R.drawable.like_icon);
}
}
});
holder.collectionImageRipple.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
#Override
public void onComplete(RippleView rippleView) {
EventBus.getDefault().post(new CollectionMessageEvent(collectionData));
}
});
}
#Override
public int getItemCount() {
return mDataSet.size();
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
public static class CollectionViewHolder extends RecyclerView.ViewHolder {
TextView titleText;
ImageView collectionImage;
TextView secondaryText;
TextView likeCount;
TextView viewCount;
ImageView profileImage;
ImageView viewIcon;
RippleView collectionImageRipple;
RippleView profileImageRipple;
RippleView likeIconRipple;
ImageView likeIcon;
public CollectionViewHolder(View itemView) {
super(itemView);
// View bottombar = findById(itemView,R.id.bottomBar);
collectionImage = findById(itemView, R.id.collection_image);
collectionImageRipple = findById(itemView, R.id.collection_image_ripple);
profileImage = findById(itemView, R.id.profileimage);
profileImageRipple = findById(itemView, R.id.profileimage_ripple);
titleText = findById(itemView, R.id.title_text);
secondaryText = findById(itemView, R.id.secondary_text);
likeCount = findById(itemView, R.id.like_count);
likeIcon = findById(itemView, R.id.like_icon);
likeIconRipple = findById(itemView, R.id.like_icon_ripple);
viewCount = findById(itemView, R.id.view_count);
viewIcon = findById(itemView, R.id.view_icon);
}
}
}

Categories

Resources