Add different layout between item in RecyclerView-AndroidX - java

I want to add Different layout between item in my recyclerview, I have 3 item in first layout, and then I add second layout to item number 2, so It should have 4 item right now, (1-FirstLayout)-(2-SecondLayout)-(3FirstLayout)-(4FirstLayout), but I realize the position that I choose from my second layout replaced to the position first layout it becomes like this (1-FirstLayout)-(2-SecondLayout)-(3FirstLayout)
Iam not sure how to fix it
This is my Adapter
public class AdapterGameReview extends RecyclerView.Adapter{
public static final int TYPE_ITEM = 1;
public static final int TYPE_TOPREVIEWER = 2;
public static final int TYPE_ADSBANNER = 3;
private boolean mWithTopReviewer = true;
private boolean mWithAdsBanner = false;
private Context mContext;
private ArrayList<ModelGameReview> modelGameReviews;
private RecyclerViewClickListener mListener;
public AdapterGameReview(Context mContext, ArrayList<ModelGameReview> modelGameReviews, RecyclerViewClickListener mListener) {
this.mContext = mContext;
this.modelGameReviews = modelGameReviews;
this.mListener = mListener;
}
//Container
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = null;
if (viewType == TYPE_TOPREVIEWER) {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_gamereviewtopreviewer, null);
return new GameReviewTopReviewerViewHolder(v);
} else if (viewType == TYPE_ADSBANNER) {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_adsbannerdummy, null);
return new GameReviewAdsBannerViewHolder(v);
} else {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_gamereview, null);
return new GameReviewViewHolder(v, mListener);
}
}
//Fill Container with Model Setter Getter
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof AdapterGameReview.GameReviewTopReviewerViewHolder) {
AdapterGameReview.GameReviewTopReviewerViewHolder gameReviewTopReviewerViewHolder = (AdapterGameReview.GameReviewTopReviewerViewHolder) holder;
/*gameReviewTopReviewerViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});*/
}else if (holder instanceof AdapterGameReview.GameReviewAdsBannerViewHolder) {
AdapterFollowSavedGameReviewList.ShowmoreViewHolder showmoreViewHolder = (AdapterFollowSavedGameReviewList.ShowmoreViewHolder) holder;
} else {
final GameReviewViewHolder GameReviewViewHolder = (GameReviewViewHolder) holder;
final ModelGameReview modelGameReviewX = modelGameReviews.get(position);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.mipmap.ic_launcher);
requestOptions.error(R.drawable.bug);
requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
requestOptions.centerCrop();
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = inputFormat.parse(modelGameReviewX.getGamedate());
} catch (ParseException e) {
e.printStackTrace();
}
CharSequence niceDateStr = DateUtils.getRelativeTimeSpanString(date.getTime(), Calendar.getInstance().getTimeInMillis(), DateUtils.MINUTE_IN_MILLIS);
//Set
GameReviewViewHolder.TVGameDate.setText(niceDateStr);
GameReviewViewHolder.TVGameTitle.setText(modelGameReviewX.getGametitle());
GameReviewViewHolder.TVGameDescription.setText(modelGameReviewX.getGamedescription());
Glide.with(mContext).load(modelGameReviewX.getGameimage())
.apply(requestOptions)
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
GameReviewViewHolder.ProgressLoadPhoto.setVisibility(View.GONE);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
GameReviewViewHolder.ProgressLoadPhoto.setVisibility(View.GONE);
return false;
}
})
.transition(DrawableTransitionOptions.withCrossFade())
.into(GameReviewViewHolder.IMGGameImage);
GameReviewViewHolder.TVSeenCounter.setText(String.valueOf(modelGameReviewX.getSeencounter()));
GameReviewViewHolder.TVCommentCounter.setText(String.valueOf(modelGameReviewX.getCommentcounter()));
GameReviewViewHolder.TVLikeCounter.setText(String.valueOf(modelGameReviewX.getLikecounter()));
if (modelGameReviewX.getIscomment() == 0) {
GameReviewViewHolder.IMGCommentView.setImageResource(R.drawable.comment_off);
} else if (modelGameReviewX.getIscomment() == 1) {
GameReviewViewHolder.IMGCommentView.setImageResource(R.drawable.comment_on);
}
if (modelGameReviewX.getIslike() == 0) {
GameReviewViewHolder.IMGLikeView.setImageResource(R.drawable.heart_off);
} else if (modelGameReviewX.getIslike() == 1) {
GameReviewViewHolder.IMGLikeView.setImageResource(R.drawable.heart_on);
}
if (modelGameReviewX.getIsbookmark() == 0) {
GameReviewViewHolder.IMGBookmarkView.setImageResource(R.drawable.saved_off);
GameReviewViewHolder.IMGBookmarkView.setVisibility(View.GONE);
} else if (modelGameReviewX.getIsbookmark() == 1) {
GameReviewViewHolder.IMGBookmarkView.setImageResource(R.drawable.saved_on);
}
GameReviewViewHolder.TVReviewer.setText(modelGameReviewX.getReviewer());
}
}
#Override
public int getItemCount() {
int itemCount = 0;
if(mWithTopReviewer == true){
itemCount++;
}
itemCount = modelGameReviews.size();
return itemCount;
}
//TYPE_ITEM
public class GameReviewViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView TVGameDate;
TextView TVGameTitle;
TextView TVGameDescription;
ImageView IMGGameImage;
TextView TVSeenCounter;
TextView TVCommentCounter;
TextView TVLikeCounter;
ImageView IMGSeenView;
ImageView IMGCommentView;
ImageView IMGLikeView;
TextView TVReviewer;
ProgressBar ProgressLoadPhoto;
ImageView IMGBookmarkView;
private RelativeLayout ROWGameReviewContainer;
private RecyclerViewClickListener mListener;
public GameReviewViewHolder(View itemView, RecyclerViewClickListener listener) {
super(itemView);
TVGameDate = itemView.findViewById(R.id.TV_GameDate);
TVGameTitle = itemView.findViewById(R.id.TV_GameTitle);
TVGameDescription = itemView.findViewById(R.id.TV_GameDescription);
IMGGameImage = itemView.findViewById(R.id.IMG_GameImage);
TVSeenCounter = itemView.findViewById(R.id.TV_SeenCounter);
TVCommentCounter = itemView.findViewById(R.id.TV_CommentCounter);
TVLikeCounter = itemView.findViewById(R.id.TV_LikeCounter);
IMGSeenView = itemView.findViewById(R.id.IMG_SeenView);
IMGCommentView = itemView.findViewById(R.id.IMG_CommentView);
IMGLikeView = itemView.findViewById(R.id.IMG_LikeView);
TVReviewer = itemView.findViewById(R.id.TV_Reviewer);
ProgressLoadPhoto = itemView.findViewById(R.id.Progress_LoadPhoto);
IMGBookmarkView = itemView.findViewById(R.id.IMG_BookmarkView);
ROWGameReviewContainer = itemView.findViewById(R.id.ROW_GameReviewContainer);
mListener = listener;
ROWGameReviewContainer.setOnClickListener(this);
IMGCommentView.setOnClickListener(this);
IMGLikeView.setOnClickListener(this);
IMGBookmarkView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ROW_GameReviewContainer:
mListener.onRowGameReviewContainerClick(ROWGameReviewContainer, getAdapterPosition());
break;
case R.id.IMG_CommentView:
mListener.onRowCommentViewClick(IMGCommentView, getAdapterPosition());
break;
case R.id.IMG_LikeView:
mListener.onRowLikeViewClick(IMGLikeView, getAdapterPosition());
break;
case R.id.IMG_BookmarkView:
mListener.onRowBookmarkViewClick(IMGBookmarkView, getAdapterPosition());
break;
default:
break;
}
}
}
public interface RecyclerViewClickListener {
void onRowGameReviewContainerClick(View view, int position);
void onRowCommentViewClick(View view, int position);
void onRowLikeViewClick(View view, int position);
void onRowBookmarkViewClick(View view, int position);
}
//TYPE_TOPREVIEWER
public class GameReviewTopReviewerViewHolder extends RecyclerView.ViewHolder{
Button BTNToBeReviewer;
public GameReviewTopReviewerViewHolder(View itemView) {
super(itemView);
BTNToBeReviewer = itemView.findViewById(R.id.BTN_ToBeReviewer);
}
}
//TYPE_ADSBANNER
public class GameReviewAdsBannerViewHolder extends RecyclerView.ViewHolder{
public GameReviewAdsBannerViewHolder(View itemView) {
super(itemView);
}
}
#Override
public int getItemViewType(int position) {
if (mWithTopReviewer && isPositionTopReviewer(position))
return TYPE_TOPREVIEWER;
if (mWithAdsBanner && isPositionAdsBanner(position))
return TYPE_ADSBANNER;
return TYPE_ITEM;
}
public boolean isPositionTopReviewer(int position) {
return position == 1 && mWithTopReviewer;
}
public boolean isPositionAdsBanner(int position) {
return position == getItemCount() - 1 && mWithAdsBanner;
}
public void setWithTopReviewer(boolean value) {
mWithTopReviewer = value;
}
public void setWithAdsBanner(boolean value) {
mWithAdsBanner = value;
}
}
This is My Model
public class ModelGameReview implements Serializable {
private int contentpage;
private String idcontent;
private String gametitle;
private String gamedate;
private String gameimage;
private String gamedescription;
private int seencounter;
private int commentcounter;
private int likecounter;
private int iscomment;
private int islike;
private int isbookmark;
private String reviewer;
private String value;
private String message;
public ModelGameReview(int contentpage, String idcontent, String gametitle, String gamedate, String gameimage, String gamedescription, int seencounter, int commentcounter, int likecounter, int iscomment, int islike, int isbookmark, String reviewer, String value, String message) {
this.contentpage = contentpage;
this.idcontent = idcontent;
this.gametitle = gametitle;
this.gamedate = gamedate;
this.gameimage = gameimage;
this.gamedescription = gamedescription;
this.seencounter = seencounter;
this.commentcounter = commentcounter;
this.likecounter = likecounter;
this.iscomment = iscomment;
this.islike = islike;
this.isbookmark = isbookmark;
this.reviewer = reviewer;
this.value = value;
this.message = message;
}
public int getContentpage() {
return contentpage;
}
public void setContentpage(int contentpage) {
this.contentpage = contentpage;
}
public String getIdcontent() {
return idcontent;
}
public void setIdcontent(String idcontent) {
this.idcontent = idcontent;
}
public String getGametitle() {
return gametitle;
}
public void setGametitle(String gametitle) {
this.gametitle = gametitle;
}
public String getGamedate() {
return gamedate;
}
public void setGamedate(String gamedate) {
this.gamedate = gamedate;
}
public String getGameimage() {
return gameimage;
}
public void setGameimage(String gameimage) {
this.gameimage = gameimage;
}
public String getGamedescription() {
return gamedescription;
}
public void setGamedescription(String gamedescription) {
this.gamedescription = gamedescription;
}
public int getSeencounter() {
return seencounter;
}
public void setSeencounter(int seencounter) {
this.seencounter = seencounter;
}
public int getCommentcounter() {
return commentcounter;
}
public void setCommentcounter(int commentcounter) {
this.commentcounter = commentcounter;
}
public int getLikecounter() {
return likecounter;
}
public void setLikecounter(int likecounter) {
this.likecounter = likecounter;
}
public int getIscomment() {
return iscomment;
}
public void setIscomment(int iscomment) {
this.iscomment = iscomment;
}
public int getIslike() {
return islike;
}
public void setIslike(int islike) {
this.islike = islike;
}
public int getIsbookmark() {
return isbookmark;
}
public void setIsbookmark(int isbookmark) {
this.isbookmark = isbookmark;
}
public String getReviewer() {
return reviewer;
}
public void setReviewer(String reviewer) {
this.reviewer = reviewer;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

You have implemented this method wrong
#Override
public int getItemCount() {
int itemCount = 0;
if(mWithTopReviewer == true){
itemCount++;
}
itemCount = modelGameReviews.size();
return itemCount;
}
It should be something similar
#Override
public int getItemCount() {
int itemCount = modelGameReviews.size();
if(mWithTopReviewer == true){
itemCount++;
}
return itemCount;
}

Related

How to add parcelable arraylist to section recycler view adapter

In my application i'm trying to pass an parcelable array list to a sectioned recycler view adapter but inside the add method where we add sections it gives me required string error:
This is my parcelable class:
public class HostBean implements Parcelable {
public static final String EXTRA = ActivityMain.PKG + ".extra";
public static final String EXTRA_POSITION = ActivityMain.PKG + ".extra_position";
public static final String EXTRA_HOST = ActivityMain.PKG + ".extra_host";
public static final String EXTRA_TIMEOUT = ActivityMain.PKG + ".network.extra_timeout";
public static final String EXTRA_HOSTNAME = ActivityMain.PKG + ".extra_hostname";
public static final String EXTRA_BANNERS = ActivityMain.PKG + ".extra_banners";
public static final String EXTRA_PORTSO = ActivityMain.PKG + ".extra_ports_o";
public static final String EXTRA_PORTSC = ActivityMain.PKG + ".extra_ports_c";
public static final String EXTRA_SERVICES = ActivityMain.PKG + ".extra_services";
public static final int TYPE_GATEWAY = 0;
public static final int TYPE_COMPUTER = 1;
public int deviceType = TYPE_COMPUTER;
public int isAlive = 1;
public int position = 0;
public int responseTime = 0; // ms
public String ipAddress = null;
public String hostname = null;
public String hostsection = null;
public String hardwareAddress = NetInfo.NOMAC;
public String nicVendor = "Unknown";
public String os = "Unknown";
public HashMap<Integer, String> services = null;
public HashMap<Integer, String> banners = null;
public ArrayList<Integer> portsOpen = null;
public ArrayList<Integer> portsClosed = null;
public HostBean() {
// New object
}
public HostBean(Parcel in) {
// Object from parcel
readFromParcel(in);
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(deviceType);
dest.writeInt(isAlive);
dest.writeString(ipAddress);
dest.writeString(hostname);
dest.writeString( hostsection );
dest.writeString(hardwareAddress);
dest.writeString(nicVendor);
dest.writeString(os);
dest.writeInt(responseTime);
dest.writeInt(position);
dest.writeMap(services);
dest.writeMap(banners);
dest.writeList(portsOpen);
dest.writeList(portsClosed);
}
private void readFromParcel(Parcel in) {
deviceType = in.readInt();
isAlive = in.readInt();
ipAddress = in.readString();
hostname = in.readString();
hardwareAddress = in.readString();
nicVendor = in.readString();
os = in.readString();
hostsection=in.readString();
responseTime = in.readInt();
position = in.readInt();
services = in.readHashMap(null);
banners = in.readHashMap(null);
portsOpen = in.readArrayList(Integer.class.getClassLoader());
portsClosed = in.readArrayList(Integer.class.getClassLoader());
}
#SuppressWarnings("unchecked")
public static final Creator CREATOR = new Creator() {
public HostBean createFromParcel(Parcel in) {
return new HostBean(in);
}
public HostBean[] newArray(int size) {
return new HostBean[size];
}
};
}
This is my simple adapter class:
public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.SimpleViewHolder> {
private final Context mContext;
private ArrayList<HostBean> mData;
final HostBean host = new HostBean();
public void add(HostBean s,int position) {
position = position == -1 ? getItemCount() : position;
host.hostsection=s;
mData.add(position,s); //at this line of code i'm getting error
notifyItemInserted(position);
}
public void remove(int position){
if (position < getItemCount() ) {
mData.remove(position);
notifyItemRemoved(position);
}
}
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
public final TextView mac;
public final TextView vendor;
public final TextView ip;
public SimpleViewHolder(View view) {
super(view);
ip = (TextView) view.findViewById(R.id.ip);
mac = (TextView) view.findViewById(R.id.mac);
vendor = (TextView) view.findViewById(R.id.vendor);
}
}
public SimpleAdapter(Context context, List<HostBean> data) {
mContext = context;
if (data != null)
mData = new ArrayList<HostBean>();
}
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.list_host, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(SimpleViewHolder holder, final int position) {
holder.ip.setText( (CharSequence) mData.get(position) );
holder.mac.setText( "" );
holder.vendor.setText( "" );
}
#Override
public int getItemCount() {
return mData.size();
}
}
This is my simple sectioned recyclerview adapter class:
public class SimpleSectionedRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context mContext;
private static final int SECTION_TYPE = 0;
private boolean mValid = true;
private int mSectionResourceId;
private int mTextResourceId;
private LayoutInflater mLayoutInflater;
private RecyclerView.Adapter mBaseAdapter;
private SparseArray<Section> mSections = new SparseArray<Section>();
public SimpleSectionedRecyclerViewAdapter(Context context, int sectionResourceId, int textResourceId,
RecyclerView.Adapter baseAdapter) {
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mSectionResourceId = sectionResourceId;
mTextResourceId = textResourceId;
mBaseAdapter = baseAdapter;
mContext = context;
mBaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
mValid = mBaseAdapter.getItemCount()>0;
notifyDataSetChanged();
}
#Override
public void onItemRangeChanged(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeChanged(positionStart, itemCount);
}
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeInserted(positionStart, itemCount);
}
#Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeRemoved(positionStart, itemCount);
}
});
}
public static class SectionViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public SectionViewHolder(View view, int mTextResourceid) {
super(view);
title = (TextView) view.findViewById(mTextResourceid);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int typeView) {
if (typeView == SECTION_TYPE) {
final View view = LayoutInflater.from(mContext).inflate(mSectionResourceId, parent, false);
return new SectionViewHolder(view,mTextResourceId);
}else{
return mBaseAdapter.onCreateViewHolder(parent, typeView -1);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder sectionViewHolder, int position) {
if (isSectionHeaderPosition(position)) {
((SectionViewHolder)sectionViewHolder).title.setText(mSections.get(position).title);
}else{
mBaseAdapter.onBindViewHolder(sectionViewHolder,sectionedPositionToPosition(position));
}
}
#Override
public int getItemViewType(int position) {
return isSectionHeaderPosition(position)
? SECTION_TYPE
: mBaseAdapter.getItemViewType(sectionedPositionToPosition(position)) +1 ;
}
public static class Section {
int firstPosition;
int sectionedPosition;
CharSequence title;
public Section(int firstPosition, CharSequence title) {
this.firstPosition = firstPosition;
this.title = title;
}
public CharSequence getTitle() {
return title;
}
}
public void setSections(Section[] sections) {
mSections.clear();
Arrays.sort(sections, new Comparator<Section>() {
#Override
public int compare(Section o, Section o1) {
return (o.firstPosition == o1.firstPosition)
? 0
: ((o.firstPosition < o1.firstPosition) ? -1 : 1);
}
});
int offset = 0; // offset positions for the headers we're adding
for (Section section : sections) {
section.sectionedPosition = section.firstPosition + offset;
mSections.append(section.sectionedPosition, section);
++offset;
}
notifyDataSetChanged();
}
public int positionToSectionedPosition(int position) {
int offset = 0;
for (int i = 0; i < mSections.size(); i++) {
if (mSections.valueAt(i).firstPosition > position) {
break;
}
++offset;
}
return position + offset;
}
public int sectionedPositionToPosition(int sectionedPosition) {
if (isSectionHeaderPosition(sectionedPosition)) {
return RecyclerView.NO_POSITION;
}
int offset = 0;
for (int i = 0; i < mSections.size(); i++) {
if (mSections.valueAt(i).sectionedPosition > sectionedPosition) {
break;
}
--offset;
}
return sectionedPosition + offset;
}
public boolean isSectionHeaderPosition(int position) {
return mSections.get(position) != null;
}
#Override
public long getItemId(int position) {
return isSectionHeaderPosition(position)
? Integer.MAX_VALUE - mSections.indexOfKey(position)
: mBaseAdapter.getItemId(sectionedPositionToPosition(position));
}
#Override
public int getItemCount() {
return (mValid ? mBaseAdapter.getItemCount() + mSections.size() : 0);
}
}
This is how is initialize the arraylist:
hosts = new ArrayList<HostBean>();
This is my activity code for setting adapter to recyclerview:
RecyclerView list =findViewById(R.id.output);
list.setHasFixedSize( true );
list.setLayoutManager( new LinearLayoutManager( this ) );
list.addItemDecoration(new DividerItemDecoration(this,LinearLayoutManager.VERTICAL));
SimpleAdapter mAdapter = new SimpleAdapter(this,hosts);
List<SimpleSectionedRecyclerViewAdapter.Section> sections =
new ArrayList<SimpleSectionedRecyclerViewAdapter.Section>();
//Sections
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(0,"Know Devices"));
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(5,"Unknown Devices"));
SimpleSectionedRecyclerViewAdapter.Section[] dummy = new SimpleSectionedRecyclerViewAdapter.Section[sections.size()];
SimpleSectionedRecyclerViewAdapter mSectionedAdapter = new
SimpleSectionedRecyclerViewAdapter(this,R.layout.section,R.id.section_text,mAdapter);
mSectionedAdapter.setSections(sections.toArray(dummy));
list.setAdapter( mSectionedAdapter );
Your mData is an ArrayList<>. Therefore you can not pass key, value for that. You can only pass one param, either key or value. List is not a map.
private ArrayList<HostBean> mData;
mData.add(position,s); // Can not do this
If you want a key value relationship, then use HashMap like this.
private HashMap<Integer, HostBean> mData;

How to show multiple data source data in single recycle view or adapter using LazyLoading?

The above image is a simple design that I want to develop.
I have four type of different data with different view type like the below image enter image description here. but that is not a problem. problem is the data will come from different API with lazy loading like when user scroll the list from recycle view it will grab the data from the server. My question is how to combine them in a single adapter because I need to use lazy loading .so I can't load whole data at a time so I need to call the different type of API like goal-list API, appraisal API, post API etc. When user scroll. anyone can give me an idea with example. How can I handle that? Also when user will scroll it will call another api likeCount and comment count also. Currently, In my, I am calling single API and show that in the single recycle view. Currently, I am using android architecture component LiveData
Fragment :
public class NewsFeedFragment extends FcaFragment {
private View view;
private RecyclerView postRecyclerView;
private PostsAdapter postsAdapter;
private List<Post> posts;
private TimelineViewModel timelineViewModel;
private ImageView addPostView;
private View addPostPanel;
private long lastApiCallTime;
private SwipyRefreshLayout swipeRefresh;
private long lastScroolItemInPost= 0;
public NewsFeedFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(lastScroolItemInPost < 1) {
initViewModel(1 , 0 , true);
lastScroolItemInPost = 1;
}else {
initViewModel(((int) lastScroolItemInPost + 5), lastScroolItemInPost , true);
lastScroolItemInPost += 5;
}
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ownerActivity);
view = inflater.inflate(R.layout.fragment_news_feed, container, false);
postRecyclerView = (RecyclerView) view.findViewById(R.id.postRecyclerView);
postRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView postRecyclerView, int dx, int dy) {
super.onScrolled(postRecyclerView, dx, dy);
int lastVisiableItemInPostList = linearLayoutManager.findLastVisibleItemPosition();
if(lastScroolItemInPost < lastVisiableItemInPostList)
{
if(lastScroolItemInPost == 1)
{
initViewModel((int) (lastScroolItemInPost + 2), ( lastScroolItemInPost - 2 ) , false);
lastScroolItemInPost += 2;
}else{
initViewModel((int) (lastScroolItemInPost + 2), ( lastScroolItemInPost - 2 ) , false );
lastScroolItemInPost += 2;
}
}
}
});
posts = new ArrayList<>();
postRecyclerView.setLayoutManager(linearLayoutManager);
postsAdapter = new PostsAdapter(ownerActivity,posts,timelineViewModel);
postRecyclerView.setAdapter(postsAdapter);
swipeRefresh = (SwipyRefreshLayout) view.findViewById(R.id.swipeRefresh);
swipeRefresh.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh(SwipyRefreshLayoutDirection direction) {
if(direction == SwipyRefreshLayoutDirection.TOP){
timelineViewModel.fetchPosts2();
}
if(direction == SwipyRefreshLayoutDirection.BOTTOM){
timelineViewModel.fetchPosts();
}
}
});
return view;
}
private void initViewModel(int lastVisiableItemInPostList , long lastScroolItemInPost , boolean isFirstTimeOpenFeedFragment) {
TimelineViewModel.Factory factory = new TimelineViewModel.Factory(UserPreferences.getToken(ownerActivity), TaskUtils.getMySelfContact(ownerActivity));
timelineViewModel = ViewModelProviders.of(this,factory).get(TimelineViewModel.class);
timelineViewModel.getPostList().observe(this, new Observer<List<Post>>() {
#Override
public void onChanged(#Nullable List<Post> posts) {
postsAdapter.setPostList(posts);
swipeRefresh.setRefreshing(false);
}
});
timelineViewModel.getPostDeleted().observe(this, new Observer<Boolean>() {
#Override
public void onChanged(#Nullable Boolean aBoolean) {
if(aBoolean){
postsAdapter.setPostList(Post.getAll());
}
}
});
timelineViewModel.init( lastVisiableItemInPostList , lastScroolItemInPost ,isFirstTimeOpenFeedFragment);
}
}
ViewModel :
public class TimelineViewModel extends FCViewModel implements PostDetailsDownloadManager.PostDetailDownloadedListener,OnContactReceivedListner{
public TimelineViewModel(String token,Contact user){
super(token);
this.user = user;
post = new MutableLiveData<>();
postDeleted = new MutableLiveData<>();
}
public void init(int lastVisiableItemInPostList , long lastScroolItemInPost , boolean isFirstTimeOpenFeedFragment){
repository =
//postDetailsDownloadManager = ServiceLocator.getServiceLocator().postDetailsDownloadManager;
likePostDownloadManager = ServiceLocator.getServiceLocator().likePostDownloadManager;
likePostDownloadManager.setPostDetailDownloadedListener(new DataDownloadManager.DataDownloadedListener<LikePostTouple>() {
#Override
public void onDataDownloaded(List<LikePostTouple> dataTouple) {
TimelineViewModel.this.post.setValue(Post.getAll());
}
#Override
public void onSingleDataDownloaded(LikePostTouple dataTouple) {
}
});
postDetailDownloadManager = ServiceLocator.getServiceLocator().postDetailDownloadManager;
postDetailDownloadManager.setPostDetailDownloadedListener(new DataDownloadManager.DataDownloadedListener<PostTouple>() {
#Override
public void onDataDownloaded(List<PostTouple> dataTouple) {
TimelineViewModel.this.post.setValue(Post.getAll());
}
#Override
public void onSingleDataDownloaded(PostTouple dataTouple) {
}
});
post.setValue(Post.getAll());
if(isFirstTimeOpenFeedFragment)
{
fetchPosts2();
}
try {
if(Post.getAll().size() > 0)
{
List<Post> tempPosts = Post.getAll();
List<Post> passList = tempPosts.subList( (int) lastScroolItemInPost ,lastVisiableItemInPostList);
fetchLikesOfPosts(passList);
}else{
fetchLikesOfPosts(Post.getAll());
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d("Testing Injecting", repository.toString());
}
public LiveData<List<Post>> getPostList() {
return post;
}
public MutableLiveData<Boolean> getPostDeleted() {
return postDeleted;
}
boolean isContactFetched = false;
public void fetchPosts(){
if(Contact.getAll().size() < 1){
fetchContacts();
return;
}
Map<String,Object> requestData = new HashMap<>();
requestData.put("type",1);
requestData.put("cpid",Post.getLastPid());
isDataLoading = true;
repository.getData(new Repository.DataFetchedListener<List<Post>>() {
#Override
public void onDataFetched(List<Post> posts) {
isDataLoading = false;
Log.d("fetched posts",""+posts.size());
post.setValue(Post.getAll());
fetchPostDetails(posts);
if(posts.size() > 0){
fetchLikesOfPosts(posts);
}
}
},requestData);
}
private boolean isDataLoading = false;
public void fetchPosts2(){
if(Contact.getAll().size() < 1){
fetchContacts();
return;
}
Map<String,Object> requestData = new HashMap<>();
requestData.put("type",2);
requestData.put("cpid", Post.getFirstPid()); // cpid means cursor pid
isDataLoading = true;
repository.getData(new Repository.DataFetchedListener<List<Post>>() {
#Override
public void onDataFetched(List<Post> posts) {
isDataLoading = false;
Log.d("fetched posts",""+posts.size());
post.setValue(Post.getAll());
fetchPostDetails(posts);
if(posts.size() > 0){
fetchLikesOfPosts(posts);
}
}
},requestData);
}
public boolean isDataLoading() {
return isDataLoading;
}
private void fetchContacts() {
contactRepository.getData(new Repository.DataFetchedListener<List<Contact>>() {
#Override
public void onDataFetched(List<Contact> data) {
if(data.size()>0 && !isContactFetched) {
fetchPosts2();
isContactFetched = true;
}
}
},null);
}
#NonNull
private PostTouple getPostToubleFromPost(Post post) throws JSONException {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(post);
JSONObject postJson = new JSONObject(json);
return new PostTouple(postJson,post.getPid());
}
#NonNull
private LikePostTouple getLkePostToupleFromPost(Post post) throws JSONException {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(post);
JSONObject postJson = new JSONObject(json);
return new LikePostTouple(postJson,post.getPid());
}
public void giveLike(String token, final long pid){
Map<String,Object> requestData = new HashMap<>();
requestData.put("token",token);
requestData.put("pid",Long.toString(pid));
likeRepository.postData(new Repository.DataFetchedListener<Post>() {
#Override
public void onDataFetched(Post data) {
Log.d("Like post", data.toString());
Post post = getPostById(pid);
post.setLikes(data.getLikes());
post.setComments(data.getComments());
TimelineViewModel.this.post.setValue(TimelineViewModel.this.post.getValue());
fetchLikesOfLikedPost(data);
}
},requestData);
}
private void fetchLikesOfLikedPost(Post data) {
try {
likePostDownloadManager.addItemInQueue(getLkePostToupleFromPost(data));
likePostDownloadManager.startDownload();
} catch (JSONException e) {
e.printStackTrace();
}
}
private Post getPostById(long pid){
List<Post> posts = post.getValue();
for(Post post : posts){
if(post.getPid()==pid){
return post;
}
}
return null;
}
public Contact getSenderContactFromComment(Post post) {
if(post.getPqrc().equals(user.getUserId())){
return user;
}
Contact contact = Contact.getByUserId(post.getPqrc());
return contact;
}
public String getDescriptionForType5(Post post,String message){
try {
PostDetail postDetail = PostDetail.getByPostId(post.getPid());
if(postDetail!=null) {
String qrc = JSonUtils.qrcFromCntOfPostDetails(postDetail.getContent());
int sid = JSonUtils.skillidFromCntOfPostDetails(postDetail.getContent());
if (qrc == null || sid == 0) {
return "";
}
SkillDb skill = SkillDb.getBySId(Integer.toString(sid));
Contact contact = getPosterContact(post.getPqrc());
return contact.getName() + " " + message + " " + skill.getSkillName() + ".";
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public String getDescriptionForPost(Post post, String message){
if(post.getCtype()==1){
return post.getDescr();
}
if(post.getCtype() == 2){
String postDetail = getContent(post);
if (postDetail != null) return Html.fromHtml(""+postDetail+"").toString();
}
if(post.getCtype()==5){
return getDescriptionForType5(post, message);
}
return "";
}
#Nullable
public String getContent(Post post) {
PostDetail postDetail = PostDetail.getByPostId(post.getPid());
if(postDetail!=null){
return postDetail.getContent();
}
return null;
}
public Contact getPosterContact(String qrc){
try {
String userqrc = user.getUserId();
if (userqrc.equals(qrc)) {
return user;
}
}catch (Exception e){
e.printStackTrace();
}
try {
return Contact.getByUserId(qrc);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public void fetchUrlPreview(String url, final UrlMetaDataFetchListener metaDataFetchListener){
String modifiedUrl = !url.contains("http://")&&!url.contains("https://")? "http://"+url : url;
TextCrawler textCrawler = new TextCrawler();
LinkPreviewCallback linkPreviewCallback = new LinkPreviewCallback() {
#Override
public void onPre() {
}
#Override
public void onPos(SourceContent sourceContent, boolean b) {
String imageUrl = sourceContent.getImages().isEmpty()? "" : sourceContent.getImages().get(0);
metaDataFetchListener.onMetaDataFetched(sourceContent.getTitle(),sourceContent.getDescription(), imageUrl);
}
};
textCrawler.makePreview(linkPreviewCallback, modifiedUrl,1);
}
public interface UrlMetaDataFetchListener{
void onMetaDataFetched(String title, String description, String imageUrl);
}
#Override
public void onPostDownloaded(PostTouple postTouple) {
this.post.setValue(Post.getAll());
}
#Override
public void onContactsReceived() {
fetchPosts();
}
public void deletePost(long pid) {
Map<String, Object> requestData = new HashMap<>();
requestData.put("token",token);
requestData.put("pid",pid);
repository.postData(new Repository.DataFetchedListener<Post>() {
#Override
public void onDataFetched(Post data) {
postDeleted.setValue(data!=null);
}
},requestData);
}
public boolean isMyPost(Post post){
return user.getUserId().equals(post.getPqrc());
}
public static class Factory extends ViewModelProvider.NewInstanceFactory {
private String token;
private Contact user;
public Factory(String token,Contact user) {
this.token = token;
this.user = user;
}
#Override
public <T extends ViewModel> T create(Class<T> modelClass) {
return (T) new TimelineViewModel(token,user);
}
}
}
Adapter :
public class PostsAdapter extends RecyclerView.Adapter {
private Context context;
private List<Post> postList;
private int[] badges = {R.drawable.badge1, R.drawable.badge2, R.drawable.badge3};
private List<Integer> randomNumbers = Utils.getRandomNumberList(2,true);
private ArrayDeque<Integer> randomQueue = new ArrayDeque<>(randomNumbers);
private static Map<Long,URLPreview> urlPreviewMap = new HashMap<>();
private TimelineViewModel timelineViewModel;
public PostsAdapter(Context context, List<Post> postList, TimelineViewModel timelineViewModel){
super();
this.context = context;
this.postList = postList;
this.timelineViewModel = timelineViewModel;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.post_item_layout, null);
PostViewHolder postViewHolder = new PostViewHolder(view);
postViewHolder.setIsRecyclable(false);
return postViewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final Post post = postList.get(position);
final PostViewHolder postViewHolder = (PostViewHolder) holder;
final String postDetail = timelineViewModel.getDescriptionForPost(post,context.getResources().getString(R.string.postType5message));
setPostDescription(post, postViewHolder, postDetail);
handlePreviewVisibility(post, postViewHolder);
postViewHolder.setLikes(""+post.getLikes()+" Likes");
postViewHolder.setCommentCount("" + post.getComments() + " Comments");
postViewHolder.setSupDescription("Posted By System");
int randomNumber = getRandomNumber();
postViewHolder.setBadgeIcon(badges[randomNumber]);
setPostLikedIndicator(post, postViewHolder);
postViewHolder.getLikeButtonWrapper().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
giveLikeToPost(post);
if(post.getIsLiked() == 0) {
post.setLikes(post.getLikes() + 1);
postViewHolder.setLikes("" + post.getLikes() + " Likes");
post.setIsLiked(1);
setPostLikedIndicator(post, postViewHolder);
}
}
});
postViewHolder.getCommentPanel().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CommentPostFragment fragment = CommentPostFragment.GetInstance(post.getPid());
ViewUtils.launchFragmentKeepingInBackStack(context,fragment);
}
});
Contact contact = timelineViewModel.getPosterContact(post.getPqrc());
if(contact!=null && TaskUtils.isNotEmpty(contact.getImageToken())){
Utils.setImageToImageView(postViewHolder.getPosterImage(),timelineViewModel.getToken(),contact.getImageToken());
postViewHolder.getPosterNameTextView().setText(contact.getName());
}
postViewHolder.getPostingDate().setText(Utils.getDateFromMilliseconds(post.getdC()));
if(post.getCtype() != 3)
{
postViewHolder.contentImage.setVisibility(View.GONE);
postViewHolder.fullScreenIndicatorIcon.setVisibility(View.GONE);
}
if(post.getCtype() == 3){
setContentOfType3(post, postViewHolder);
}
}
#Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
PostViewHolder viewHolder = (PostViewHolder) holder;
viewHolder.pTitle.setText("");
viewHolder.pDescription.setText("");
viewHolder.pImage.setImageDrawable(null);
}
private void handlePreviewVisibility(Post post, PostViewHolder postViewHolder) {
if(post.getCtype()==2){
postViewHolder.preview.setVisibility(View.VISIBLE);
}else{
postViewHolder.preview.setVisibility(View.GONE);
}
}
private void handleShowingOptionsIcon(Post post, PostViewHolder postViewHolder) {
if(post.getCtype()!=5 && timelineViewModel.isMyPost(post)){
postViewHolder.options.setVisibility(View.VISIBLE);
}else{
postViewHolder.options.setVisibility(View.GONE);
}
}
private void giveLikeToPost(Post post) {
post.setLikes(post.getLikes()+1);
post.setIsLiked(1);
//notifyDataSetChanged();
timelineViewModel.giveLike(UserPreferences.getToken(context),post.getPid());
}
private void setPostLikedIndicator(Post post, PostViewHolder postViewHolder) {
if(post.getIsLiked()==1) {
postViewHolder.getLikeButton().setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.ic_like_red, null));
}else{
postViewHolder.getLikeButton().setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.ic_like_filled, null));
}
}
private void setPostDescription(final Post post, final PostViewHolder postViewHolder, final String postDetail) {
if(post.getCtype()==2){
String postDescription = "<p>"+ post.getDescr()+"</p>";
postViewHolder.description.setText( Html.fromHtml(postDescription +""+postDetail+"") );
postViewHolder.descriptionContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = !postDetail.contains("http://")&&!postDetail.contains("https://")? "http://"+postDetail : postDetail;
Uri uri = Uri.parse(url);
context.startActivity(new Intent(Intent.ACTION_VIEW,uri));
}
});
URLPreview urlPreview = null;
if((urlPreview=urlPreviewMap.get(post.getPid()))==null) {
timelineViewModel.fetchUrlPreview(postDetail, new TimelineViewModel.UrlMetaDataFetchListener() {
#Override
public void onMetaDataFetched(String title, String description, String imageUrl) {
showURLPreview(title, description, imageUrl, postViewHolder);
urlPreviewMap.put(post.getPid(),new URLPreview(title,description,imageUrl));
}
});
}else {
showURLPreview(urlPreview.getTitle(),urlPreview.getDescription(),urlPreview.getImageUrl(),postViewHolder);
}
}else if(post.getCtype() == 3)
{
String postDescription = post.getDescr();
postViewHolder.description.setText(postDescription);
}
else {
postViewHolder.setDescription(postDetail);
}
}
private void initImageClickListener(final ImageView imageView, final String pictureLink) {
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<String> pictureLinks = new ArrayList<String>();
pictureLinks.add(pictureLink);
int[] screenLocation = new int[2];
imageView.getLocationOnScreen(screenLocation);
ImagePagerFragment imagePagerFragment = ImagePagerFragment.newInstance(pictureLinks, 0, screenLocation, imageView.getWidth(), imageView.getHeight());
ViewUtils.launchPopUpFragmentUpdated(context, imagePagerFragment);
}
});
}
private void showURLPreview(String title, String description, String imageUrl, PostViewHolder postViewHolder) {
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(!TaskUtils.isEmpty(imageUrl)) {
Picasso.with(context)
.load(imageUrl)
.into(postViewHolder.pImage);
}
view.findViewById(R.id.description);
postViewHolder.pTitle.setText(title);
postViewHolder.pDescription.setText(description);
}
#Override
public int getItemCount() {
return postList.size();
}
private int getRandomNumber(){
if(!randomQueue.isEmpty()){
return randomQueue.poll();
}
randomQueue = new ArrayDeque<>(randomNumbers);
return randomQueue.poll();
}
public void setPostList(List<Post> postList) {
this.postList = postList;
notifyDataSetChanged();
Log.d("Data rec", postList.size()+"");
}
class PostViewHolder extends RecyclerView.ViewHolder implements PopupMenu.OnMenuItemClickListener {
}
public void setLikes(String likes) {
this.likes.setText(likes);
}
public void setCommentCount(String commentCount)
{
this.commentCount.setText(commentCount);
}
public void setDescription(String description){
this.description.setText(description);
}
public void setSupDescription(String subDescription){
this.supDescription.setText(subDescription);
}
public void setBadgeIcon(int resID){
Utils.setImageViewFromResource(badgeIcon,resID);
}
public ImageView getLikeButton() {
return likeButton;
}
public RelativeLayout getLikeButtonWrapper()
{
return likeButtonWrapper;
}
public ImageView getCommentButton() {
return commentButton;
}
public ImageView getPosterImage() {
return posterImage;
}
public TextView getPosterNameTextView() {
return posterNameTextView;
}
public TextView getPostingDate() {
return postingDate;
}
public RelativeLayout getCommentPanel() {
return commentPanel;
}
#Override
public boolean onMenuItemClick(MenuItem item) {
timelineViewModel.deletePost(postList.get(getAdapterPosition()).getPid());
return false;
}
}
}

Autocompletetextview not showing dropdown with custom adapter

I have an autocompletetextview. I am getting results from an API and sending to the adapter on textchanged.
Here is the adapter.
public class ProductSearchAdapter extends BaseAdapter implements Filterable {
private Context context;
private ArrayList<ProductListModel> originalList;
private ArrayList<ProductListModel> suggestions = new ArrayList<>();
private Filter filter = new CustomFilter();
public ProductSearchAdapter(Context context, ArrayList<ProductListModel> originalList) {
this.context = context;
this.originalList = originalList;
}
#Override
public int getCount() {
return suggestions.size(); // Return the size of the suggestions list.
}
#Override
public Object getItem(int position) {
return originalList.get(position).getName();
}
#Override
public long getItemId(int position) {
return 0;
}
/**
* This is where you inflate the layout and also where you set what you want to display.
* Here we also implement a View Holder in order to recycle the views.
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.product_search_row, parent, false);
holder = new ViewHolder();
holder.textViewProductName = (TextView) convertView.findViewById(R.id.textViewProductName);
holder.imageViewProductImage = (ImageView) convertView.findViewById(R.id.imageViewProductImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textViewProductName.setText(originalList.get(position).getName());
Picasso.with(context)
.load(originalList.get(position).getImagesSmall().get(0).getSrc())
.into(holder.imageViewProductImage);
return convertView;
}
#Override
public Filter getFilter() {
return filter;
}
private static class ViewHolder {
ImageView imageViewProductImage;
TextView textViewProductName;
}
/**
* Our Custom Filter Class.
*/
private class CustomFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
suggestions.clear();
if (originalList != null && constraint != null) { // Check if the Original List and Constraint aren't null.
for (int i = 0; i < originalList.size(); i++) {
if (originalList.get(i).getName().toLowerCase().contains(constraint)) { // Compare item in original list if it contains constraints.
suggestions.add(originalList.get(i)); // If TRUE add item in Suggestions.
}
}
}
FilterResults results = new FilterResults(); // Create new Filter Results and return this to publishResults;
results.values = suggestions;
results.count = suggestions.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
Now the problem is the dropdown is not showing up. Whereas if I try the same autocompletetextview with array adapter, its showing up.
Here is the activity part I am calling the api from:
autoCompleteTextViewSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().length() > 0) {
hitSearchAPI(charSequence.toString());
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
On API response:
final GsonBuilder gsonBuilder = new GsonBuilder();
final Gson gson = gsonBuilder.create();
productList = gson.fromJson(responseString, ProductListModel[].class);
arrayListProducts = new ArrayList<ProductListModel>(Arrays.asList(productList));
productsSearchAdapter = new ProductSearchAdapter(MainActivity.this, arrayListProducts);
autoCompleteTextViewSearch.setThreshold(1);
autoCompleteTextViewSearch.setAdapter(productsSearchAdapter);
Same textview working with array adapter but not with custom adapter.
ProductListModel:
public class ProductListModel {
String _id;
String name;
String color;
String description;
int credits;
ProductItemModel category;
ArrayList<ProductItemModel> subcategories;
ProductItemModel fit;
ProductBrandModel brand;
ArrayList<ProductItemModel> rules;
ProductBrandModel condition;
ArrayList<ProductImagesModel> images;
ArrayList<ProductItemModel> size;
ArrayList<ProductImagesModel> imagesSmall;
String userId;
long time_created;
long time_approved;
long time_featured;
long time_rejected;
boolean approved;
boolean rejected;
boolean featured;
int status;
ProductUserProfileModel user_profile;
String rejected_reason_id;
String categoryId;
int likes;
boolean likedBy;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getCredits() {
return credits;
}
public void setCredits(int credits) {
this.credits = credits;
}
public ProductItemModel getCategory() {
return category;
}
public void setCategory(ProductItemModel category) {
this.category = category;
}
public ArrayList<ProductItemModel> getSubcategories() {
return subcategories;
}
public void setSubcategories(ArrayList<ProductItemModel> subcategories) {
this.subcategories = subcategories;
}
public ProductItemModel getFit() {
return fit;
}
public void setFit(ProductItemModel fit) {
this.fit = fit;
}
public ProductBrandModel getBrand() {
return brand;
}
public void setBrand(ProductBrandModel brand) {
this.brand = brand;
}
public ArrayList<ProductItemModel> getRules() {
return rules;
}
public void setRules(ArrayList<ProductItemModel> rules) {
this.rules = rules;
}
public ProductBrandModel getCondition() {
return condition;
}
public void setCondition(ProductBrandModel condition) {
this.condition = condition;
}
public ArrayList<ProductImagesModel> getImages() {
return images;
}
public void setImages(ArrayList<ProductImagesModel> images) {
this.images = images;
}
public ArrayList<ProductItemModel> getSize() {
return size;
}
public void setSize(ArrayList<ProductItemModel> size) {
this.size = size;
}
public ArrayList<ProductImagesModel> getImagesSmall() {
return imagesSmall;
}
public void setImagesSmall(ArrayList<ProductImagesModel> imagesSmall) {
this.imagesSmall = imagesSmall;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public long getTime_created() {
return time_created;
}
public void setTime_created(long time_created) {
this.time_created = time_created;
}
public long getTime_approved() {
return time_approved;
}
public void setTime_approved(long time_approved) {
this.time_approved = time_approved;
}
public long getTime_featured() {
return time_featured;
}
public void setTime_featured(long time_featured) {
this.time_featured = time_featured;
}
public long getTime_rejected() {
return time_rejected;
}
public void setTime_rejected(long time_rejected) {
this.time_rejected = time_rejected;
}
public boolean isApproved() {
return approved;
}
public void setApproved(boolean approved) {
this.approved = approved;
}
public boolean isRejected() {
return rejected;
}
public void setRejected(boolean rejected) {
this.rejected = rejected;
}
public boolean isFeatured() {
return featured;
}
public void setFeatured(boolean featured) {
this.featured = featured;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public ProductUserProfileModel getUser_profile() {
return user_profile;
}
public void setUser_profile(ProductUserProfileModel user_profile) {
this.user_profile = user_profile;
}
public String getRejected_reason_id() {
return rejected_reason_id;
}
public void setRejected_reason_id(String rejected_reason_id) {
this.rejected_reason_id = rejected_reason_id;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
public boolean isLikedBy() {
return likedBy;
}
public void setLikedBy(boolean likedBy) {
this.likedBy = likedBy;
}
}
You need to add toString() method to your model so the AutoCompleteTextView can compare between the typed String and the returned value.
if you are looking by name the toString() needs to return it :
#Override
public String toString() {
return name ;
}
}

Adding Arraylist to custom object not updating values in android

In the below android activity, trying to display data in a view pager and it is working as expected.
But in loadItemsForSuppliers method, when i am adding SupplierAndItemList object to it's arraylist, value returned from getInventoriesByItemDetails method is not updating properly rather takes last value always.
Can some body assist me what's wrong here ?
public class ScreenSlidePagerActivity extends BaseActivity {
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
private Dealer dealerObject;
private ArrayList<ItemDetail> itemDetails;
private List<Dealer> supplierList;
private ArrayList<SupplierAndItemList> supplierAndItemLists = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
dealerObject = getIntent().getParcelableExtra(UiConstants.DEALER_OBJECT);
itemDetails = getIntent().getParcelableArrayListExtra("itemDetails");
supplierList = dealerObject.getParentSalesPoints(this,dealerObject.getServerId());
loadItemsForSuppliers();
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(),supplierAndItemLists);
mPager.setAdapter(mPagerAdapter);
}
private void loadItemsForSuppliers() {
for (Dealer dealer : supplierList) {
ArrayList<ItemDetail> inventories = new ArrayList<>();
SupplierAndItemList supplierAndItem = new SupplierAndItemList();
supplierAndItem.setDealerName(dealer.getDealerName());
supplierAndItem.setSelectedItemList(getInventoriesByItemDetails(dealer, inventories));
supplierAndItemLists.add(supplierAndItem);
}
}
private ArrayList<ItemDetail> getInventoriesByItemDetails(Dealer dealer, ArrayList<ItemDetail> inventories) {
for (ItemDetail id : itemDetails) {
DealerInventory dealerInventory = new DealerInventory();
dealerInventory = dealerInventory.getLastModifiedInventory(this, id.getItemId(), dealer.getId());
if (dealerInventory != null) {
if (dealerInventory.getQuantity() >= 0) {
id.setParentSalesPointLastStock(String.valueOf(dealerInventory.getQuantity()));
id.setParentSalesPointLastStockTakingDate(dealerInventory.getStockTakingDate());
}
} else {
id.setParentSalesPointLastStock(UiConstants.NA);
id.setParentSalesPointLastStockTakingDate(UiConstants.NA);
}
inventories.add(id);
}
return inventories;
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<SupplierAndItemList> supplierAndItemList;
public ScreenSlidePagerAdapter(FragmentManager fm, ArrayList<SupplierAndItemList> supplierAndItemList) {
super(fm);
this.supplierAndItemList = supplierAndItemList;
}
#Override
public Fragment getItem(int position) {
SupplierAndItemList supplierAndItems = supplierAndItemList.get(position);
ScreenSlidePageFragment f = new ScreenSlidePageFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("supplierAndItems",supplierAndItems.getSelectedItemList());
bundle.putString("supplierName",supplierAndItems.getDealerName());
f.setArguments(bundle);
return f;
}
#Override
public int getCount() {
return supplierAndItemList.size();
}
}
}
SupplierAndItemList class
public class SupplierAndItemList implements Parcelable {
public String dealerName;
public ArrayList<ItemDetail> selectedItemList;
public SupplierAndItemList() {
selectedItemList = new ArrayList<>();
}
public String getDealerName() {
return dealerName;
}
public void setDealerName(String dealerName) {
this.dealerName = dealerName;
}
public ArrayList<ItemDetail> getSelectedItemList() {
return selectedItemList;
}
public void setSelectedItemList(ArrayList<ItemDetail> itemList) {
this.selectedItemList = itemList;
}
protected SupplierAndItemList(Parcel in) {
dealerName = in.readString();
selectedItemList = in.readArrayList(ItemDetail.class.getClassLoader());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(dealerName);
dest.writeList(selectedItemList);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<SupplierAndItemList> CREATOR = new Parcelable.Creator<SupplierAndItemList>() {
#Override
public SupplierAndItemList createFromParcel(Parcel in) {
return new SupplierAndItemList(in);
}
#Override
public SupplierAndItemList[] newArray(int size) {
return new SupplierAndItemList[size];
}
};
}
ItemDetail class
public class ItemDetail implements Parcelable {
public int itemId;
public String itemName;
public String salesPointLastStock;
public String salesPointLastStockTakingDate;
public String parentSalesPointLastStock;
public String parentSalesPointLastStockTakingDate;
public IDStockInput idStockInput;
public IDReturnInput idReturnInput;
public IDOrderInput idOrderInput;
public boolean isSelected;
public boolean isSelected() {
return isSelected;
}
public void setIsSelected(boolean isUpdated) {
this.isSelected = isUpdated;
}
public String getParentSalesPointLastStockTakingDate() {
return parentSalesPointLastStockTakingDate;
}
public void setParentSalesPointLastStockTakingDate(String parentSalesPointLastStockTakingDate) {
this.parentSalesPointLastStockTakingDate = parentSalesPointLastStockTakingDate;
}
public String getParentSalesPointLastStock() {
return parentSalesPointLastStock;
}
public void setParentSalesPointLastStock(String parentSalesPointLastStock) {
this.parentSalesPointLastStock = parentSalesPointLastStock;
}
#NonNull
public int getItemId() {
return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
#NonNull
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
#NonNull
public String getSalesPointLastStock() {
return salesPointLastStock;
}
public void setSalesPointLastStock(String salesPointLastStock) {
this.salesPointLastStock = salesPointLastStock;
}
#NonNull
public String getSalesPointLastStockTakingDate() {
return salesPointLastStockTakingDate;
}
public void setSalesPointLastStockTakingDate(String salesPointLastStockTakingDate) {
this.salesPointLastStockTakingDate = salesPointLastStockTakingDate;
}
public IDStockInput getIdStockInput() {
return idStockInput;
}
public void setIdStockInput(IDStockInput idStockInput) {
this.idStockInput = idStockInput;
}
public IDReturnInput getIdReturnInput() {
return idReturnInput;
}
public void setIdReturnInput(IDReturnInput idReturnInput) {
this.idReturnInput = idReturnInput;
}
public IDOrderInput getIdOrderInput() {
return idOrderInput;
}
public void setIdOrderInput(IDOrderInput idOrderInput) {
this.idOrderInput = idOrderInput;
}
public ItemDetail() {
idStockInput = new IDStockInput();
idReturnInput = new IDReturnInput();
idOrderInput = new IDOrderInput();
}
protected ItemDetail(Parcel in) {
itemId = in.readInt();
itemName = in.readString();
salesPointLastStock = in.readString();
salesPointLastStockTakingDate = in.readString();
parentSalesPointLastStock = in.readString();
parentSalesPointLastStockTakingDate = in.readString();
isSelected =in.readInt()==1;
idStockInput = (IDStockInput) in.readValue(IDStockInput.class.getClassLoader());
idReturnInput = (IDReturnInput) in.readValue(IDReturnInput.class.getClassLoader());
idOrderInput = (IDOrderInput) in.readValue(IDOrderInput.class.getClassLoader());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(itemId);
dest.writeString(itemName);
dest.writeString(salesPointLastStock);
dest.writeString(salesPointLastStockTakingDate);
dest.writeString(parentSalesPointLastStock);
dest.writeString(parentSalesPointLastStockTakingDate);
dest.writeInt(isSelected ? 1 : 0);
dest.writeValue(idStockInput);
dest.writeValue(idReturnInput);
dest.writeValue(idOrderInput);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<ItemDetail> CREATOR = new Parcelable.Creator<ItemDetail>() {
#Override
public ItemDetail createFromParcel(Parcel in) {
return new ItemDetail(in);
}
#Override
public ItemDetail[] newArray(int size) {
return new ItemDetail[size];
}
};
}
I have go through your method I have found some assigning value issue
private void loadItemsForSuppliers() {
for (Dealer dealer : supplierList) {
ArrayList<ItemDetail> inventories = new ArrayList<>();
SupplierAndItemList supplierAndItem = new SupplierAndItemList();
supplierAndItem.setDealerName(dealer.getDealerName());
supplierAndItem.setSelectedItemList(getInventoriesByItemDetails(dealer, inventories));
supplierAndItemLists.add(supplierAndItem);
}
}
private ArrayList<ItemDetail> getInventoriesByItemDetails(Dealer dealer, ArrayList<ItemDetail> inventories) {
for (ItemDetail id : itemDetails) {
DealerInventory dealerInventory = new DealerInventory();
dealerInventory = dealerInventory.getLastModifiedInventory(this, id.getItemId(), dealer.getId());
if (dealerInventory != null) {
if (dealerInventory.getQuantity() >= 0) {
id.setParentSalesPointLastStock(String.valueOf(dealerInventory.getQuantity()));
id.setParentSalesPointLastStockTakingDate(dealerInventory.getStockTakingDate());
}
} else {
id.setParentSalesPointLastStock(UiConstants.NA);
id.setParentSalesPointLastStockTakingDate(UiConstants.NA);
}
inventories.add(id); // do this
}
return inventories; // you are not assigning value anywhere;
}
You are not assigning value to the inventories in getInventoriesByItemDetails. I think you should add item through inventories.add(id);
Check it , Hope this help
Set
mPager.setOffscreenPageLimit(1);

Ho to change ListView items count?

I have a ListView with the sections. And when there is a section, then it takes the place of another. That is, if the ListView items count 30, the section takes the place of the first paragraph, and it turns out that the show only 29 points.
Here is a picture, which shows clearly
Tried TYPE_MAX_COUNT = 2, 3. Without confusing.
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
I think getViewTypeCount() is triggered after getView().
private List<VacancyModel> vacancyModelList;
private LayoutInflater inflater;
private SQLHelper sqlHelper;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_ITEM = 0;
private int rowType;
public static String saveLastDate;
private int newRecs = 0;
public SuitableAdapter(Context context, int resource, List<VacancyModel> objects) {
super(context, resource, objects);
vacancyModelList = objects;
sqlHelper = new SQLHelper(getContext());
inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull final ViewGroup parent) {
ViewHolder holder = null;
rowType = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch (rowType) {
case TYPE_SEPARATOR:
convertView = inflater.inflate(R.layout.suitable_separator_layout, null);
holder.headerTv = (TextView) convertView.findViewById(R.id.section_header);
break;
case TYPE_ITEM:
convertView = inflater.inflate(R.layout.row_layout, null);
holder.tvProfession = (TextView) convertView.findViewById(R.id.tvProfession);
holder.tvHeader = (TextView) convertView.findViewById(R.id.tvHeader);
holder.tvSalary = (TextView) convertView.findViewById(R.id.tvSalary);
holder.tvDate = (TextView) convertView.findViewById(R.id.tvPostCr);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (getItemViewType(position) == TYPE_SEPARATOR) {
holder.headerTv = (TextView) convertView.findViewById(R.id.section_header);
if (newRecs == 1) {
holder.headerTv.setText("Новые вакансии");
newRecs = 0;
} else {
holder.headerTv.setText("Ранее просмотренные");
}
}
if (getItemViewType(position) == TYPE_ITEM) {
final VacancyModel model = vacancyModelList.get(position);
holder.tvProfession.setText(model.getProfession());
holder.tvHeader.setText(model.getHeader());
holder.tvSalary.setText(model.getSalary());
holder.tvDate.setText(model.getDate());
Date date;
try {
if (saveLastDate == null) {
saveLastDate = model.getDate();
} else {
date = stringToDate(saveLastDate);
if (date.before(stringToDate(model.getDate()))) {
saveLastDate = model.getDate();
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return convertView;
}
#Override
public int getItemViewType(int position) {
if (GlobalData.LoadDate(getContext()) == null) {
return TYPE_ITEM;
} else {
VacancyModel model = getItem(position);
if (model != null) {
String newString = model.getDate();
String lastString = GlobalData.LoadDate(getContext());
Date newDate = null;
Date lastDate = null;
try {
newDate = stringToDate(newString);
lastDate = stringToDate(lastString);
} catch (ParseException e) {
e.printStackTrace();
}
assert newDate != null;
if (newDate.equals(lastDate)) {
return TYPE_SEPARATOR;
} else if (position == 0 && newDate.after(lastDate)) {
newRecs = 1;
return TYPE_SEPARATOR;
} else {
return TYPE_ITEM;
}
} else {
return TYPE_ITEM;
}
}
}
#Override
public int getViewTypeCount() {
return 3;
}
#Override
public int getCount() {
return vacancyModelList.size();
}
private Date stringToDate(String string) throws ParseException {
return new SimpleDateFormat(("yyyy-MM-dd HH:mm:ss"), Locale.getDefault()).parse(string);
}
private static class ViewHolder {
private TextView tvProfession;
private TextView tvHeader;
private TextView tvSalary;
private TextView tvDate;
private TextView headerTv;
}
VacancyModel
public class VacancyModel implements Serializable{
private String profession;
private String header;
private String salary;
private String date;
public VacancyModel() {
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
public String getSalary() {
if (salary.equals("0") || salary.isEmpty() || salary.equals("null")){
return "empty";
}
else {
return salary;
}
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
Question: What I am doing wrong and how to change ListView`s count?
The listItem you are sending in should have the type field as well. So what I am suggesting is instead of doing date check manipulation inside listview. you can do it prior before adding data to RecyclerView.
Adding two more Field to your Serializable Data:
public class VacancyModel implements Serializable{
private String profession;
private String header;
private String salary;
private String date;
// set setter and getter for both, by default isHeading will be false,
private boolean isHeading;
private String heading;
public VacancyModel() {
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
public String getSalary() {
if (salary.equals("0") || salary.isEmpty() || salary.equals("null")){
return "empty";
}
else {
return salary;
}
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
Do the following thing inside your activity inside activity:
private void generateListHeading(List<VacancyModel> original_vacany_list)
{
List<VacancyModel> vacancy_type_new_record;
VacancyModel model = new vacacyModel();
model.setIsHeading(true);
model.setHeading("New Record");
vacancy_type_new_record.add(model);
List<VacancyModel> vacancy_type_watched;
model = new vacacyModel();
model.setIsHeading(true);
model.setHeading("Watched");
vacancy_type_watched.add(model);
List<VacancyModel> new_vacancy_list;
for(VacanyModel data:original_vacany_list)
{
//do your date condition check here
if(data.getDate==newDate)
{
vacancy_type_new_record.add(data)
} else
{
vacancy_type_watched.add(data)
}
}
//once the whole condition check is add both list to new list
new_vacancy_list.addAll(vacancy_type_new_record);
new_vacancy_list.addAll(vacancy_type_watched);
//now the item count will be 32. in the format heading ,data ,heading,data
adapter.setUpdateddata(new_vacancy_list);
}
Adapter.class:
vacanyModelList = new ArrayList<>();
public SuitableAdapter(Context context, int resource) {
super(context, resource, objects);
//don't set your object in constructor
sqlHelper = new SQLHelper(getContext());
inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull final ViewGroup parent) {
ViewHolder holder = null;
rowType = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch (rowType) {
case TYPE_SEPARATOR:
convertView = inflater.inflate(R.layout.suitable_separator_layout, null);
holder.headerTv = (TextView) convertView.findViewById(R.id.section_header);
break;
case TYPE_ITEM:
convertView = inflater.inflate(R.layout.row_layout, null);
holder.tvProfession = (TextView) convertView.findViewById(R.id.tvProfession);
holder.tvHeader = (TextView) convertView.findViewById(R.id.tvHeader);
holder.tvSalary = (TextView) convertView.findViewById(R.id.tvSalary);
holder.tvDate = (TextView) convertView.findViewById(R.id.tvPostCr);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (getItemViewType(position) == TYPE_SEPARATOR) {
holder.headerTv = (TextView) convertView.findViewById(R.id.section_header);
if (newRecs == 1) {
holder.headerTv.setText("Новые вакансии");
newRecs = 0;
} else {
holder.headerTv.setText("Ранее просмотренные");
}
}
if (getItemViewType(position) == TYPE_ITEM) {
final VacancyModel model = vacancyModelList.get(position);
holder.tvProfession.setText(model.getProfession());
holder.tvHeader.setText(model.getHeader());
holder.tvSalary.setText(model.getSalary());
holder.tvDate.setText(model.getDate());
Date date;
try {
if (saveLastDate == null) {
saveLastDate = model.getDate();
} else {
date = stringToDate(saveLastDate);
if (date.before(stringToDate(model.getDate()))) {
saveLastDate = model.getDate();
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return convertView;
}
#Override
public int getItemViewType(int position) {
VacancyModel model = getItem(position);
if (model.isHeading) {
return TYPE_SEPARATOR;
} else {
return TYPE_ITEM;
}
}
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return vacancyModelList.size();
}
private Date stringToDate(String string) throws ParseException {
return new SimpleDateFormat(("yyyy-MM-dd HH:mm:ss"), Locale.getDefault()).parse(string);
}
private static class ViewHolder {
private TextView tvProfession;
private TextView tvHeader;
private TextView tvSalary;
private TextView tvDate;
private TextView headerTv;
}
public void setUpdatedData(List<VacancyModel> updated_list)
{
this.vacancyModelList = updated_list;
notifyDataSetChanged();
}

Categories