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 ;
}
}
Related
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;
}
Good day. I need to implement parcelable in Model class.Currently it is Serializable. for now only setdate and set title if thare If any one can help. please edit code.
MainActivity.java
Document document = Jsoup.connect("http://feeds.bbci.co.uk/urdu/rss.xml").ignoreHttpErrors(true).get();
Elements itemElements = document.getElementsByTag("item");
for (int i = 0; i < itemElements.size(); i++) {
Element item = itemElements.get(i);
NewsItem newsItem = new NewsItem();
newsItem.setDate(item.child(4).text());
newsItem.setTitle(item.child(0).text());
newsItemsList.add(newsItem);
}
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter = new NewsAdaptor(Main2Activity.this,
newsItemsList);
lvRss.setAdapter(adapter);
}
});
return null;
}
NewsItem.java //model class
public class NewsItem implements Serializable {
String imagePath;
String title;
String link;
String date;
public NewsItem () {
}
public String getImagePath () {
return imagePath;
}
public void setImagePath ( String imagePath ) {
this.imagePath = imagePath;
}
public String getTitle () {
return title;
}
public void setTitle ( String title ) {
this.title = title;
}
public String getLink () {
return link;
}
public void setLink ( String link ) {
this.link = link;
}
public String getDate () {
return date;
}
public void setDate ( String date ) {
this.date = date;
}
NewsAdapter.java
public class NewsAdaptor extends BaseAdapter {
private int textSize;
TextView tvtitle;
private int color;
Context context;
public NewsAdaptor ( Context context, ArrayList <NewsItem> newsList ) {
this.context = context;
this.newsList = newsList;
this.color = Color.RED;
}
ArrayList<NewsItem> newsList;
#Override
public int getCount () {
return newsList.size();
}
#Override
public Object getItem ( int position ) {
return newsList.get(position);
}
#Override
public long getItemId ( int position ) {
return 0;
}
#Override
public View getView ( int position, View convertView, ViewGroup parent ) {
if (convertView == null){
convertView=View.inflate(context, R.layout.newsitemlist_layout,null);
}
NewsItem currentNews = newsList.get(position);
ImageView iv1 = (ImageView) convertView.findViewById(R.id.mainimg);
TextView tvdate = (TextView) convertView.findViewById(R.id.pubDateid);
Picasso.with(context).load(currentNews.getImagePath()).placeholder(R.drawable.expressimg).into(iv1);
tvdate.setText(currentNews.getDate());
tvtitle = (TextView) convertView.findViewById(R.id.textView1id);
tvtitle.setText(currentNews.getTitle());
tvtitle.setTextColor(color);
return convertView;
}
public void setTextColor(int color) {
this.color = color;
}
Check this Parcelable NewsItem:
public class NewsItem implements Parcelable {
String imagePath;
String title;
String link;
String date;
public NewsItem() {
}
protected NewsItem(Parcel in) {
imagePath = in.readString();
title = in.readString();
link = in.readString();
date = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(imagePath);
dest.writeString(title);
dest.writeString(link);
dest.writeString(date);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<NewsItem> CREATOR = new Creator<NewsItem>() {
#Override
public NewsItem createFromParcel(Parcel in) {
return new NewsItem(in);
}
#Override
public NewsItem[] newArray(int size) {
return new NewsItem[size];
}
};
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
Interface:
public interface BabService {
#GET("bab.php")
Call<Respon> tampil(#Query("imam") String imam);
}
Respon:
public class Respon {
private String value;
private List<BabResult> resultBab;
public String getValue() {
return value;
}
public List<BabResult> getResultBab() { return resultBab; }
}
Result:
public class BabResult {
private String id_bab;
private String id_kitab;
private String bab;
public String getId_bab() { return id_bab; }
public String getId_kitab() {
return id_kitab;
}
public String getBab() {
return bab;
}
}
Adapter:
public class BabAdapter extends RecyclerView.Adapter<BabAdapter.ViewHolder>
{
private Context context;
private List<BabResult> results;
private String idBab, judulBab;
private int no;
public BabAdapter(Context context, List<BabResult> results) {
this.context = context;
this.results = results;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_bab, parent, false);
ViewHolder holder = new ViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(position % 2 != 0){
holder.vBab.setBackgroundResource(R.color.ijo);
}else{
holder.vBab.setBackgroundResource(R.color.oren);
}
no = position + 1;
BabResult result = results.get(position);
idBab = result.getId_bab();
judulBab = result.getBab();
holder.tvNo.setText(no);
holder.tvBab.setText(judulBab);
}
#Override
public int getItemCount() {
if(results == null){
return 4;
}
return results.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View vBab;
private TextView tvBab, tvNo;
public ViewHolder(View itemView) {
super(itemView);
vBab = (View) itemView.findViewById(R.id.v_bab);
tvNo = (TextView) itemView.findViewById(R.id.tv_no);
tvBab = (TextView) itemView.findViewById(R.id.tv_bab);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, HadisList.class);
i.putExtra("id", idBab);
i.putExtra("bab", judulBab);
i.putExtra("no", no);
context.startActivity(i);
}
});
}
}
}
Activity:
public class MenuBab extends AppCompatActivity {
public static final String URL = "http://mi3bpolinema.000webhostapp.com/";
private List<BabResult> results = new ArrayList<>();
private BabAdapter babAdapter;
private ProgressBar pbLoading;
private RecyclerView rvBab;
private TextView tvImam;
private String imam, namaImam;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_bab);
if(getSupportActionBar() != null){
getSupportActionBar().hide();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Intent intent = getIntent();
if(intent != null){
if(intent.getStringExtra("imam") != null){
imam = intent.getStringExtra("imam");
namaImam = intent.getStringExtra("nama");
}
}
pbLoading = (ProgressBar) findViewById(R.id.pb_loading);
rvBab = (RecyclerView) findViewById(R.id.rv_bab);
tvImam = (TextView) findViewById(R.id.tv_imam);
tvImam.setText(namaImam);
babAdapter = new BabAdapter(this, results);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
rvBab.setLayoutManager(mLayoutManager);
rvBab.setItemAnimator(new DefaultItemAnimator());
rvBab.setAdapter(babAdapter);
loadDataBab();
}
#Override
protected void onResume() {
super.onResume();
loadDataBab();
}
private void loadDataBab() {
Retrofit retrofit = new Retrofit
.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
BabService api = retrofit.create(BabService.class);
Call<Respon> call = api.tampil(imam);
call.enqueue(new Callback<Respon>() {
#Override
public void onResponse(Call<Respon> call, Response<Respon> response) {
String value = response.body().getValue();
pbLoading.setVisibility(View.GONE);
if (value.equals("1")) {
results = response.body().getResultBab();
babAdapter = new BabAdapter(MenuBab.this, results);
rvBab.setAdapter(babAdapter);
}
}
#Override
public void onFailure(Call<Respon> call, Throwable t) {
}
});
}
}
On retrofit get result null, but when I run in website get result like this:
{"value":1,"result":[{"id_bab":"4","id_kitab":"1","bab":"Wudhu"},
{"id_bab":"8","id_kitab":"1","bab":"Shalat"},
{"id_bab":"15","id_kitab":"1","bab":"Puasa"}]}
using this link.
You need to use Model class in this way
now you can get API Result
Response Model Class
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.ArrayList;
public class Response implements Serializable{
#SerializedName("value")
private String value;
#SerializedName("result")
private ArrayList<BabResult> resultBab;
public String getValue() {
return value;
}
public ArrayList<BabResult> getResultBab() {
return resultBab;
}
public void setValue(String value) {
this.value = value;
}
public void setResultBab(ArrayList<BabResult> resultBab) {
this.resultBab = resultBab;
}
public class BabResult {
#SerializedName("id_bab")
private String id_bab;
#SerializedName("id_kitab")
private String id_kitab;
#SerializedName("bab")
private String bab;
public String getId_bab() {
return id_bab;
}
public void setId_bab(String id_bab) {
this.id_bab = id_bab;
}
public String getId_kitab() {
return id_kitab;
}
public void setId_kitab(String id_kitab) {
this.id_kitab = id_kitab;
}
public String getBab() {
return bab;
}
public void setBab(String bab) {
this.bab = bab;
}
}
}
Respon class
public class Respon
{
private ArrayList<Result> result;
private String value;
public ArrayList<Result> getResult ()
{
return result;
}
public void setResult ( ArrayList<Result> result)
{
this.result = result;
}
public String getValue ()
{
return value;
}
public void setValue (String value)
{
this.value = value;
}
#Override
public String toString()
{
return "ClassPojo [result = "+result+", value = "+value+"]";
}
public class Result
{
private String id_kitab;
private String bab;
private String id_bab;
public String getId_kitab ()
{
return id_kitab;
}
public void setId_kitab (String id_kitab)
{
this.id_kitab = id_kitab;
}
public String getBab ()
{
return bab;
}
public void setBab (String bab)
{
this.bab = bab;
}
public String getId_bab ()
{
return id_bab;
}
public void setId_bab (String id_bab)
{
this.id_bab = id_bab;
}
#Override
public String toString()
{
return "ClassPojo [id_kitab = "+id_kitab+", bab = "+bab+", id_bab =
"+id_bab+"]";
}
}
}
Check this way data null or not and add arraylist
private void loadDataBab() {
Retrofit retrofit = new Retrofit
.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
BabService api = retrofit.create(BabService.class);
Call<Respon> call = api.tampil(imam);
call.enqueue(new Callback<Respon>() {
#Override
public void onResponse(Call<Respon> call, Response<Respon> response) {
if (response.isSuccessful())
if (response.body() != null)
pbLoading.setVisibility(View.GONE);
if (response.body().getValue().equalsIgnoreCase("1")) {
results.addAll(response.body().getResult());
babAdapter = new BabAdapter(MenuBab.this, results);
rvBab.setAdapter(babAdapter);
}
}
#Override
public void onFailure(Call<Respon> call, Throwable t) {
}
});
}
Pass the array in your Respon class like this ..
public class Respon {
private String value;
private BabResult [] result;
public String getValue() {
return value;
}
public BabResult [] getResultBab() { return result; }
}
and in your loadDataBab method ..
private List<BabResult> results = new ArrayList<>();
private void loadDataBab() {
Retrofit retrofit = new Retrofit
.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface api = retrofit.create(RequestInterface.class);
Call<Respon> call = api.tampil("1");
call.enqueue(new Callback<Respon>() {
#Override
public void onResponse(Call<Respon> call, Response<Respon> response) {
String value = response.body().getValue();
if (value.equals("1")) {
results = new ArrayList<>(Arrays.asList(response.body().getResultBab()));
}
}
#Override
public void onFailure(Call<Respon> call, Throwable t) {
}
});
}
I change Respon to :
public class Respon {
private String value;
private List<BabResult> result;
public String getValue() { return value; }
public List<BabResult> getResult() { return result; }
}
and it works. Thx :))
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);
What I want is to pass a list of list from one activity to another. Here is my approach.
Feeditem.java
public class FeedItem implements Parcelable {
private String id,status, image, timeStamp, url;
private ArrayList<CommentItem> commentItems;
public FeedItem() {
}
protected FeedItem(Parcel in) {
id = in.readString();
status = in.readString();
image = in.readString();
timeStamp = in.readString();
url = in.readString();
if(commentItems!=null) {
in.createTypedArrayList(CommentItem.CREATOR);
}
}
public static final Creator<FeedItem> CREATOR = new Creator<FeedItem>() {
#Override
public FeedItem createFromParcel(Parcel in) {
return new FeedItem(in);
}
#Override
public FeedItem[] newArray(int size) {
return new FeedItem[size];
}
};
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getImge() {
return image;
}
public void setImge(String image) {
this.image = image;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public ArrayList<CommentItem> getCommentItems() {
return commentItems;
}
public void setCommentItems(ArrayList<CommentItem> commentItems)
{
this.commentItems=commentItems;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(status);
dest.writeString(image);
dest.writeString(timeStamp);
dest.writeString(url);
dest.writeTypedList(commentItems);
}}
CommentItem.java
public class CommentItem implements Parcelable{
private String id,comment, from, timeStamp;
public CommentItem() {
}
protected CommentItem(Parcel in) {
id = in.readString();
comment = in.readString();
from = in.readString();
timeStamp = in.readString();
}
public static final Creator<CommentItem> CREATOR = new Creator<CommentItem>() {
#Override
public CommentItem createFromParcel(Parcel in) {
return new CommentItem(in);
}
#Override
public CommentItem[] newArray(int size) {
return new CommentItem[size];
}
};
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(comment);
dest.writeString(from);
dest.writeString(timeStamp);
}}
ReceivingActivity.java
ArrayList<CommentItem> commentItems;
FeedItem feedItem;
commentItems=new ArrayList<>();
Bundle bundle=getIntent().getExtras();
feedItem=bundle.getParcelable("status");
if(feedItem.getCommentItems()!=null) { //help here
commentItems = feedItem.getCommentItems();
}
SendingActivity.java
Button getComments=(Button)convertView.findViewById(R.id.commentsbutton);
getComments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(activity, CommentActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("status", item); //item is feeditem
i.putExtras(bundle);
activity.startActivity(i);
}
});
I am able to get all the attributes of the feeditem except the list which is giving me null in the receiving activity. Could someone please help me out with this. Thanks in advance.
I think the problem is that you're only reading in the list if it is already non-null:
if(commentItems!=null) {
in.createTypedArrayList(CommentItem.CREATOR);
}
If it's null, which it will be at that point, it doesn't get set. Just remove the non-null check and I think it will work.
commentItems = in.createTypedArrayList(CommentItem.CREATOR);