I'm always getting this error when i'm setting the finish method inside adapter.
11-28 09:46:09.661 8636-8646/? E/art: Failed sending reply to debugger: Broken pipe
11-28 09:46:17.709 8636-8636/com.juandirection E/InputEventReceiver: Exception dispatching input event.
11-28 09:46:17.709 8636-8636/com.juandirection E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
11-28 09:46:17.709 8636-8636/com.juandirection E/MessageQueue-JNI: java.lang.ClassCastException: com.juandirection.variables.Global cannot be cast to com.juandirection.ActivityCategorySelected
I tried to remove all item insde OnRatingChanged but the error remains the same.
public class AdapterPOI extends RecyclerView.Adapter<AdapterPOI.MainViewHolder> {
private List<ModelPoi> poiDatas;
private List<ModelImage> imageDatas;
private List<ModelComments> commentDatas;
private List<ModelFavorite> favoriteDatas;
private List<ModelAccounts> accountDatas;
private LayoutInflater inflater;
private Context context;
int viewType = 0;
int add;
int cCounter = 0;
int[] routeImg = {R.drawable.ic_resto_route, R.drawable.ic_sights_route, R.drawable.ic_transport_route, R.drawable.ic_hotel_route,
R.drawable.ic_gas_route, R.drawable.ic_school_route, R.drawable.ic_entertainment_route,
R.drawable.ic_shop_route, R.drawable.ic_atm_route, R.drawable.ic_bank_route, R.drawable.ic_hospital_route,
R.drawable.ic_pharmacy_route, R.drawable.ic_police_route, R.drawable.ic_toilet_route,};
public AdapterPOI(Context context, List<ModelPoi> poiDatas, List<ModelFavorite> favoriteDatas, List<ModelComments> commentDatas, List<ModelImage> imageDatas) {
inflater = LayoutInflater.from(context);
this.poiDatas = poiDatas;
this.context = context;
this.favoriteDatas = favoriteDatas;
this.imageDatas = imageDatas;
this.commentDatas = commentDatas;
}
#Override
public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int listViewItemType = getItemViewType(viewType);
if (listViewItemType == 0) {
return new TitleHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_title, parent, false));
}
if (listViewItemType == 1 || listViewItemType == 4 || listViewItemType == 7) {
return new HeaderHolder(LayoutInflater.from(context).inflate(R.layout.headerinformation, parent, false));
}
if (listViewItemType == 2 || listViewItemType == 3 || listViewItemType == 6) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_pictext, parent, false));
}
if (listViewItemType == 5) {
return new GalleryHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_photos, parent, false));
}
if (listViewItemType == 8) {
return new RatingHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_rating, parent, false));
}
if (listViewItemType >= 9 && listViewItemType <= 8 + commentDatas.size()) {
return new CommentsHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_comments, parent, false));
}
if (listViewItemType == 14) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_pictext, parent, false));
}
if (listViewItemType >= 9 + commentDatas.size()) {
return new TapHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_taptorate, parent, false));
}
return null;
}
#Override
public void onBindViewHolder(MainViewHolder holder, int position) {
try {
if (position == 0) {
TitleHolder tHolder = (TitleHolder) holder;
tHolder.imgType.setBackgroundResource(routeImg[Global.getPosition]);
tHolder.txtTitle.setText(Global.selectedPOI);
ModelPoi poiData = (ModelPoi) getPOI(0);
tHolder.txtType.setText(poiData.POIType);
if (favoriteDatas.size() >= 1) {
tHolder.imgFavorite.setBackgroundResource(R.drawable.ic_favorite_yellow);
tHolder.txtID.setText("1");
} else {
tHolder.imgFavorite.setBackgroundResource(R.drawable.ic_favorite_white);
tHolder.txtID.setText("0");
}
float ratingBar = 0f;
for (int i = 0; i < commentDatas.size(); i++) {
ModelComments modelComments = (ModelComments) getComment(i);
ratingBar += Float.valueOf(modelComments.rating);
}
float finalRating;
finalRating = ratingBar / commentDatas.size();
tHolder.ratingBar.setRating(finalRating);
}
if (position == 1) {
HeaderHolder hHolder = (HeaderHolder) holder;
hHolder.txtInfo.setText("Information");
}
if (position == 2) {
MyViewHolder mHolder = (MyViewHolder) holder;
ModelPoi poiData = (ModelPoi) getPOI(0);
mHolder.icon.setImageResource(R.drawable.ic_information);
mHolder.title.setText(poiData.POIInfo);
mHolder.txtID.setText("0");
}
if (position == 3) {
MyViewHolder mHolder = (MyViewHolder) holder;
ModelPoi poiData = (ModelPoi) getPOI(0);
mHolder.icon.setImageResource(R.drawable.ic_place_black_36dp);
mHolder.title.setText(poiData.POIAddress);
mHolder.txtID.setText("1");
}
if (position == 4) {
HeaderHolder hHolder = (HeaderHolder) holder;
hHolder.txtInfo.setText("Photos");
}
if (position == 5) {
GalleryHolder gHolder = (GalleryHolder) holder;
AdapterGalleryViewPoi galleryViewAdapter;
galleryViewAdapter = new AdapterGalleryViewPoi(context, imageDatas);
gHolder.gallery.setAdapter(galleryViewAdapter);
final WindowManager display = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
display.getDefaultDisplay().getMetrics(metrics);
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gHolder.gallery.getLayoutParams();
mlp.setMargins(-((metrics.widthPixels * 2 + 200) / 3), mlp.topMargin,
mlp.rightMargin, mlp.bottomMargin);
}
if (position == 6) {
MyViewHolder mHolder = (MyViewHolder) holder;
mHolder.icon.setImageResource(R.drawable.ic_local_see_black_24dp);
mHolder.title.setText("Add Photos");
mHolder.txtID.setText("2");
}
if (position == 7) {
HeaderHolder hHolder = (HeaderHolder) holder;
hHolder.txtInfo.setText("Reviews");
}
if (position == 8) {
RatingHolder mHolder = (RatingHolder) holder;
float ratingBar = 0f;
float getRate;
int progressbarE = 0, progressbarVG = 0, progressbarAVG = 0, progressbarP = 0, progressbarT = 0;
for (int i = 0; i < commentDatas.size(); i++) {
ModelComments modelComments = (ModelComments) getComment(i);
ratingBar += Float.valueOf(modelComments.rating);
getRate = Float.valueOf(modelComments.rating);
if (getRate >= 0 && getRate <= 1) {
progressbarT += getRate;
}
if (getRate > 1 && getRate <= 2) {
progressbarP += getRate;
}
if (getRate > 2 && getRate <= 3) {
progressbarAVG += getRate;
}
if (getRate > 3 && getRate <= 4) {
progressbarVG += getRate;
}
if (getRate > 4 && getRate <= 5) {
progressbarE += getRate;
}
}
mHolder.reviewTxt.setText(Global.selectedPOI);
float finalRatingBar;
finalRatingBar = ratingBar / commentDatas.size();
mHolder.ratingBarReview.setRating(finalRatingBar);
mHolder.progressbarE.setProgress(progressbarE);
mHolder.progressbarVG.setProgress(progressbarVG);
mHolder.progressbarAVG.setProgress(progressbarAVG);
mHolder.progressbarP.setProgress(progressbarP);
mHolder.progressbarT.setProgress(progressbarT);
}
if (position >= 9 && position <= 8 + commentDatas.size()) {
if (position == 9) {
cCounter = 0;
}
if (position == 10) {
cCounter = 1;
}
if (position == 11) {
cCounter = 2;
}
if (position == 12) {
cCounter = 3;
}
if (position == 13) {
cCounter = 4;
}
ModelComments modelComments = (ModelComments) getComment(cCounter);
CommentsHolder mHolder = (CommentsHolder) holder;
accountDatas = new Select().from(ModelAccounts.class)
.where(Condition.column(ModelAccounts$Table.GET_ID).is(modelComments.user_id)).queryList();
ModelAccounts modelAccounts = (ModelAccounts) getImg(0);
byte[] dataImg;
dataImg = Base64.decode(modelAccounts.img, Base64.DEFAULT);
Glide.with(context)
.load(dataImg)
.fitCenter()
.crossFade()
.into(mHolder.commentPhoto);
mHolder.commentTitle.setText(modelComments.title);
mHolder.commentDate.setText(modelComments.date);
mHolder.comments.setText(modelComments.comment);
mHolder.commentRatingbar.setRating(Float.valueOf(modelComments.rating));
mHolder.txtID.setText(modelComments.get_id);
}
if (commentDatas.size() == 5) {
if (position == 14) {
MyViewHolder mHolder = (MyViewHolder) holder;
mHolder.icon.setImageResource(R.drawable.ic_comment_black_24dp);
mHolder.title.setText("View More Comments");
mHolder.txtID.setText("3");
}
}
} catch (Exception e) {
Log.e("AdapterPOI", "" + e.toString());
}
}
public Object getImg(int position) {
return accountDatas.get(position);
}
public Object getPOI(int position) {
return poiDatas.get(position);
}
public Object getComment(int position) {
return commentDatas.get(position);
}
#Override
public int getItemCount() {
if (commentDatas.size() == 5) {
add = 16;
} else if (commentDatas.size() == 4) {
add = 14;
} else if (commentDatas.size() == 3) {
add = 13;
} else if (commentDatas.size() == 2) {
add = 12;
} else if (commentDatas.size() == 1) {
add = 11;
} else if (commentDatas.size() == 0) {
return add = 10;
}
return add;
}
#Override
public int getItemViewType(int position) {
if (position == 0) {
viewType = 0;
} else if (position == 1) {
viewType = 1;
} else if (position == 2) {
viewType = 2;
} else if (position == 3) {
viewType = 3;
} else if (position == 4) {
viewType = 4;
} else if (position == 5) {
viewType = 5;
} else if (position == 6) {
viewType = 6;
} else if (position == 7) {
viewType = 7;
} else if (position == 8) {
viewType = 8;
} else if (position == 9) {
viewType = 9;
} else if (position == 10) {
viewType = 10;
} else if (position == 11) {
viewType = 11;
} else if (position == 12) {
viewType = 12;
} else if (position == 13) {
viewType = 13;
} else if (position == 14) {
viewType = 14;
} else if (position == 15) {
viewType = 15;
}
return viewType;
}
class MyViewHolder extends MainViewHolder {
TextView title, txtID;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.poiName);
txtID = (TextView) itemView.findViewById(R.id.txtID);
icon = (ImageView) itemView.findViewById(R.id.poiIcon);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getText = txtID.getText().toString();
String getTitle = title.getText().toString();
if (getText.equalsIgnoreCase("0")) {
Global.getInfo = getTitle;
Intent intent = new Intent(context, ViewInformation.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
if (getText.equalsIgnoreCase("1")) {
Log.e("Info", "Map");
}
if (getText.equalsIgnoreCase("2")) {
Log.e("Add Photo", "Add Photo");
}
if (getText.equalsIgnoreCase("3")) {
Global.getID = null;
Intent intent = new Intent(context, ViewComment.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
});
}
}
public class HeaderHolder extends MainViewHolder {
TextView txtInfo;
public HeaderHolder(View itemView) {
super(itemView);
this.txtInfo = (TextView) itemView.findViewById(R.id.txtinfo);
}
}
public class GalleryHolder extends MainViewHolder {
Gallery gallery;
public GalleryHolder(View itemView) {
super(itemView);
this.gallery = (Gallery) itemView.findViewById(R.id.gallery);
}
}
public class TapHolder extends MainViewHolder {
RatingBar ratingBar;
public TapHolder(View itemView) {
super(itemView);
this.ratingBar = (RatingBar) itemView.findViewById(R.id.tapToRate);
this.ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
Global.setRating = rating;
Intent intent = new Intent(context, ActivityReview.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
//((ActivityCategorySelected)context).finish();
}
});
}
}
public class TitleHolder extends MainViewHolder {
ImageView imgType, imgFavorite;
TextView txtTitle, txtID, txtType;
RatingBar ratingBar;
public TitleHolder(View itemView) {
super(itemView);
final View view;
view = itemView;
imgType = (ImageView) itemView.findViewById(R.id.imgType);
imgFavorite = (ImageView) itemView.findViewById(R.id.imgFavorite);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
txtType = (TextView) itemView.findViewById(R.id.txtType);
txtID = (TextView) itemView.findViewById(R.id.txtID);
ratingBar = (RatingBar) itemView.findViewById(R.id.ratingBar);
imgFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String getID = txtID.getText().toString();
final String getType = txtType.getText().toString();
if (Global.getUserId == null) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(v.getRootView().getContext());
alertbox.setTitle("Sign In");
alertbox.setMessage("Please Sign in your account first.");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
Intent intent = new Intent(context, ActivityLogin.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
});
alertbox.show();
} else {
if (getID.equals("0")) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(v.getRootView().getContext());
alertbox.setTitle("Add This place to your Favorites?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
if (CheckNetwork.isNetworkAvailable(context)) {
txtID.setText("1");
imgFavorite.setBackgroundResource(R.drawable.ic_favorite_yellow);
addToFavorite(getType);
Thread timerThread = new Thread() {
public void run() {
try {
new DatabaseAsyncFavorites(context).execute();
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
timerThread.start();
} else {
Snackbar.make(view, "No Internet Access. Pease Connect to the Internet.", Snackbar.LENGTH_LONG).show();
}
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
});
alertbox.show();
} else {
AlertDialog.Builder alertbox = new AlertDialog.Builder(v.getRootView().getContext());
alertbox.setTitle("Remove this place from your Favorites?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
if (CheckNetwork.isNetworkAvailable(context)) {
addToFavorite(getType);
new Delete()
.from(ModelFavorite.class)
.where(Condition.column(ModelFavorite$Table.USER_ID).is(Global.getUserId))
.and(Condition.column(ModelFavorite$Table.LATITUDE).is(Global.lat)).query();
txtID.setText("0");
imgFavorite.setBackgroundResource(R.drawable.ic_favorite_white_nav);
} else {
Snackbar.make(view, "No Internet Access. Pease Connect to the Internet.", Snackbar.LENGTH_LONG).show();
}
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
});
alertbox.show();
}
}
}
});
}
}
public void addToFavorite(final String getType) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest request = new StringRequest(Request.Method.POST, Global.INSERT_FAV_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("latitude", Global.lat);
parameters.put("user_id", Global.getUserId);
parameters.put("type", getType);
return parameters;
}
};
requestQueue.add(request);
}
public class RatingHolder extends MainViewHolder {
TextView reviewTxt;
RatingBar ratingBarReview;
ProgressBar progressbarE, progressbarVG, progressbarAVG, progressbarP, progressbarT;
public RatingHolder(View itemView) {
super(itemView);
this.reviewTxt = (TextView) itemView.findViewById(R.id.reviewTxt);
this.ratingBarReview = (RatingBar) itemView.findViewById(R.id.ratingBarReview);
this.progressbarE = (ProgressBar) itemView.findViewById(R.id.progressbarE);
this.progressbarVG = (ProgressBar) itemView.findViewById(R.id.progressbarVG);
this.progressbarAVG = (ProgressBar) itemView.findViewById(R.id.progressbarAVG);
this.progressbarP = (ProgressBar) itemView.findViewById(R.id.progressbarP);
this.progressbarT = (ProgressBar) itemView.findViewById(R.id.progressbarT);
}
}
public class CommentsHolder extends MainViewHolder {
ImageView commentPhoto;
TextView commentTitle, commentDate, comments, txtID;
RatingBar commentRatingbar;
public CommentsHolder(View itemView) {
super(itemView);
this.commentPhoto = (ImageView) itemView.findViewById(R.id.commentPhoto);
this.commentTitle = (TextView) itemView.findViewById(R.id.commentTitle);
this.commentDate = (TextView) itemView.findViewById(R.id.commentDate);
this.comments = (TextView) itemView.findViewById(R.id.comments);
this.txtID = (TextView) itemView.findViewById(R.id.txtID);
this.commentRatingbar = (RatingBar) itemView.findViewById(R.id.commentRatingbar);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Global.getID = txtID.getText().toString();
Intent intent = new Intent(context, ViewComment.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
}
public class MainViewHolder extends RecyclerView.ViewHolder {
public MainViewHolder(View itemView) {
super(itemView);
}
}
}
I don't know what's causing the problem. I can use the same method on my fragments but in this adapter it's not working.
Change
adapter = new AdapterPOI(getApplicationContext(), ....)
to
adapter = new AdapterPOI(this, ....)
in the code where you call the adapter's constructor. You get the error because getApplicationContext() cannot be casted to an ActivityCategorySelected. That's an Application context; whereas the adapter is expecting an Activity's context.
Related
I am facing a issue in a horizontal recyclerview adapter.My adapter contains a imageview in postion 0 and remainings postion are empty.
When I do scroll from left to right, my images reappear from position 1 to 4 and 7.If I keeps on scrolling from left to right my imageview appears in all postion here is my adapter class.I have placed this Horizontal Recyclerview Adapter in a Vertical Recyclerview Adapter.
HomeBannerAdapter.Java
public class HomeBannerAdapter extends RecyclerView.Adapter {
private List<HomePageList> mHomepageList;
private Context mContext;
public HomeBannerAdapter(Context context, List<HomePageList> mHomepageList) {
this.mHomepageList = mHomepageList;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_single_card, viewGroup, false);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(final SingleItemRowHolder holder, final int position) {
final HomePageList singleItem = mHomepageList.get(position);
holder.mTitle.setText(singleItem.getTitle());
if (!singleItem.getBannerUrl().isEmpty()) {
Glide.with(mContext).load(singleItem.getBannerUrl().get(0)).placeholder(R.drawable.placeholder).dontAnimate().into(holder.itemImage);
Log.e("Homebanner not empty", "url" + singleItem.getBannerUrl().toString() + "position" + position);
} else {
Log.e("Homebanner url empty", "url" + singleItem.getBannerUrl().toString() + "position" + position);
}
}
#Override
public int getItemCount() {
return (null != mHomepageList ? mHomepageList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
public ImageView itemImage;
//int position = getAdapterPosition();
public TextView mTitle;
public HomePageList mHomePageList;
public SingleItemRowHolder(View view) {
super(view);
this.itemImage = (ImageView) view.findViewById(R.id.itemImage);
this.mTitle = (TextView) view.findViewById(R.id.tvTitle);
// mHomePageList = albumList.get(getPosition());
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), mTitle.getText().toString() + " position " + getPosition() + "getAdapterPosition" + getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Here is my Vertical Recyclerview Adapter
HomeDataAdapter.Java
public class HomeDataAdapter extends RecyclerView.Adapter {
private List<FormList> formList;
private Context mContext;
private List<HomePage> homePageList;
private List<ResourceType> resourceList;
final int VIEW_TYPE_HOMEPAGE = 0;
final int VIEW_TYPE_FORMPAGE = 1;
final int VIEW_TYPE_RESOURCEPAGE = 2;
public HomeDataAdapter(Context context, List<HomePage> homePageList) {
this.homePageList = homePageList;
this.mContext = context;
}
public HomeDataAdapter(Context context, List<HomePage> homePageList, List<FormList> formList) {
this.formList = formList;
this.homePageList = homePageList;
this.mContext = context;
}
public HomeDataAdapter(Context context, List<HomePage> homePageList, List<FormList> formList, List<ResourceType> resourceList) {
this.resourceList = resourceList;
this.formList = formList;
this.homePageList = homePageList;
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
switch (position) {
case VIEW_TYPE_HOMEPAGE:
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
ViewHolder homeView = new ViewHolder(v);
return homeView;
case VIEW_TYPE_FORMPAGE:
View v1 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
ViewHolder formView = new ViewHolder(v1);
return formView;
case VIEW_TYPE_RESOURCEPAGE:
View v2 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
ViewHolder resourceView = new ViewHolder(v2);
return resourceView;
}
return null;
}
#Override
public void onBindViewHolder(final ViewHolder itemRowHolder, int position) {
if (position == VIEW_TYPE_HOMEPAGE) {
HomePage mHomePage = homePageList.get(position);
Log.e("albumList", "albumList" + homePageList.get(position).toString() + "position" + position);
itemRowHolder.itemTitle.setText(mHomePage.getHeaderTitle());
HomeBannerAdapter itemListDataAdapter = new HomeBannerAdapter(mContext, mHomePage.getResults());
itemRowHolder.mRecyclerview.setHasFixedSize(true);
itemRowHolder.mRecyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.mRecyclerview.getLayoutManager().scrollToPosition(position);
itemRowHolder.mRecyclerview.getHorizontalOffset();
//itemRowHolder.mRecyclerview.scrollToPositionWithOffset(2, 20);
// itemRowHolder.mRecyclerview.getLayoutManager().smoothScrollToPosition(itemRowHolder.mRecyclerview, null, recyclerAdapter.getItemCount() - 1);
itemRowHolder.mRecyclerview.setAdapter(itemListDataAdapter);
} else if (position == VIEW_TYPE_FORMPAGE) {
position = position - 1;
FormList mFormPage = formList.get(position);
itemRowHolder.itemTitle.setText(formList.get(position).getHeaderTitle());
JobBannerAdapter itemListDataAdapter = new JobBannerAdapter(mContext, mFormPage.getResults());
itemRowHolder.mRecyclerview.setHasFixedSize(true);
itemRowHolder.mRecyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.mRecyclerview.setAdapter(itemListDataAdapter);
} else if (position == VIEW_TYPE_RESOURCEPAGE) {
position = position - 2;
ResourceType mResourceType = resourceList.get(position);
itemRowHolder.itemTitle.setText(mResourceType.getHeaderTitle());
ResourceBannerAdapter itemListDataAdapter = new ResourceBannerAdapter(mContext, resourceList.get(position).getResults());
itemRowHolder.mRecyclerview.setHasFixedSize(true);
itemRowHolder.mRecyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.mRecyclerview.setAdapter(itemListDataAdapter);
}
}
#Override
public int getItemCount() {
int homePageListSize = 0;
int formPageListSize = 0;
int resourcePageListSize = 0;
if (homePageList == null && formList == null && resourceList == null) return 0;
if (resourceList != null)
resourcePageListSize = resourceList.size();
if (formList != null)
formPageListSize = formList.size();
if (homePageList != null)
homePageListSize = homePageList.size();
if (resourcePageListSize > 0 && formPageListSize > 0 && homePageListSize > 0)
return homePageListSize + formPageListSize + resourcePageListSize; // albumlist+formlist+resourceList
if (formPageListSize > 0 && homePageListSize > 0)
return homePageListSize + formPageListSize; // albumlist+formlist
else if (resourcePageListSize > 0 && homePageListSize == 0 && formPageListSize == 0)
return resourcePageListSize; // resourceList
else if (formPageListSize > 0 && homePageListSize == 0)
return formPageListSize; // formlist
else if (formPageListSize == 0 && homePageListSize > 0)
return homePageListSize; // albumlist
else return 0;
// return (null != albumList ? albumList.size()+mFormList.size() : 0);
}
#Override
public int getItemViewType(int position) {
int homePageListSize = 0;
int formPageListSize = 0;
int resourcePageListSize = 0;
if (homePageList == null && formList == null && resourceList == null)
return super.getItemViewType(position);
if (homePageList != null)
homePageListSize = homePageList.size();
if (formList != null)
formPageListSize = formList.size();
if (resourceList != null)
resourcePageListSize = resourceList.size();
if (formPageListSize > 0 && homePageListSize > 0) {
if (position == 0) return VIEW_TYPE_HOMEPAGE;
else if (position == formPageListSize)
return VIEW_TYPE_FORMPAGE;
} else if (formPageListSize == 0 && homePageListSize > 0) {
if (position == 0) return VIEW_TYPE_HOMEPAGE;
else return VIEW_TYPE_FORMPAGE;
} else if (resourcePageListSize > 0 && formPageListSize > 0 && homePageListSize > 0) {
if (position == 0) return VIEW_TYPE_HOMEPAGE;
else if (position == 1)
return VIEW_TYPE_FORMPAGE;
else if (position == 2)
return VIEW_TYPE_RESOURCEPAGE;
}
return super.getItemViewType(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView itemTitle;
public CustomRecyclerView mRecyclerview;
public ViewHolder(View view) {
super(view);
this.itemTitle = (TextView) view.findViewById(R.id.itemTitle);
this.mRecyclerview = (CustomRecyclerView) view.findViewById(R.id.recycler_view_list);
}
}
}
I think some of your items bannerUrls is empty. So if they're empty you do not set a default empty image with Glide or manually. Here i modified your code a little. I think this'll help.
#Override
public void onBindViewHolder(final SingleItemRowHolder holder, final int position) {
final HomePageList singleItem = mHomepageList.get(position);
holder.mTitle.setText(singleItem.getTitle());
if (!TextUtils.isEmpty(singleItem.getBannerUrl())) {
Glide.with(mContext).load(singleItem.getBannerUrl().get(0)).placeholder(R.drawable.placeholder).dontAnimate().into(holder.itemImage);
Log.e("Homebanner not empty", "url" + singleItem.getBannerUrl().toString() + "position" + position);
} else {
holder.itemImage.setImageResource(R.drawable.your_place_holder_for_empty_url);
}
}
Note: Also it's a better choice to use TextUtils.isEmpty(string) to instead of string.isEmpty() to avoid Null Pointer Exception.
Edit:
Also you can let Glide to put placeholder to your ImageView by removing the if statement.
if (!TextUtils.isEmpty(singleItem.getBannerUrl()))
I think this solution'll work you for too. If you choose this way do not forget to set an empty image to Glide for your empty or null urls.
"Memory" rose quickly after open the Fragment that contains RecyclerView.When scorll up and down several times,"memory" continue to rise,and then show OOM and Force Close.
The following is the RecyclerView screenshot:
The following is my Adapter code:
I just use one RecyclerView the full page and nested a GridView at the first item;
public class CategoryPagerItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
//热门分类
public static final int VIEW_TYPE_HOT_SUB_CATE = 1;
//banner+商品横滑推荐
public static final int VIEW_TYPE_PROMOTION_LIST = 2;
public static final int VIEW_TYPE_PROMOTION_LIST_LABEL = 3;
//商品集合
public static final int VIEW_TYPE_GOODS_LIST = 4;
//商品集合标签
public static final int VIEW_TYPE_GOODS_LIST_LABEL = 5;
//加载更多
public static final int VIEW_TYPE_GOODS_LIST_MORE = 6;
public static final int COUNT_HOT_SUB_CATE=1;
public static final int COUNT_HOT_GOODS_LIST_LABEL=1;
public static final int COUNT_HOT_GOODS_LIST_MORE=1;
private String mTagId;//TabLayout的title对应的tagid
private String mTitleName;//TabLayout的title对应的name
private int mIndex = -1;//ViewPager的index
private int mLevel = 1;//级别分类
private Context mContext;
//相关的banner+横滑商品
private ArrayList<CategoryList.RelatedTagListEntity> mRelatedTagListEntityList;
//热门分类
private ArrayList<CategoryList.HotSubCategoryListEntity> mHotSubCategoryListEntityList;
//商品列表
private ArrayList<CategoryList.GoodListEntity> mGoodListEntityList;
private int mRelatedTagSize, mGoodsListSize;
private OnGoodsItemClickListener mOnGoodsItemClickListener;
public CategoryPagerItemAdapter(Context context, String tagId, String titleName, int index) {
mTagId = tagId;
mTitleName = titleName;
mIndex = index;
mContext = context;
}
public void resetData(ArrayList<CategoryList.HotSubCategoryListEntity> hotSubCategoryListEntityList,
ArrayList<CategoryList.RelatedTagListEntity> relatedTagListEntityList,
ArrayList<CategoryList.GoodListEntity> goodListEntityList, int level) {
mHotSubCategoryListEntityList = hotSubCategoryListEntityList;
mRelatedTagListEntityList = relatedTagListEntityList;
mGoodListEntityList = goodListEntityList;
mRelatedTagSize = mRelatedTagListEntityList == null ? 0 : mRelatedTagListEntityList.size();
mGoodsListSize = mGoodListEntityList == null ? 0 : mGoodListEntityList.size();
mLevel = level;
notifyDataSetChanged();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
//头部的十个分类
if (viewType == VIEW_TYPE_HOT_SUB_CATE) {
return new HotSubCateViewHolder(layoutInflater.inflate(R.layout.category_classify_item_hot_sub_cate, parent, false));
} else if (viewType == VIEW_TYPE_PROMOTION_LIST) {//banner+商品横滑推荐
return new PromotionViewHolder(layoutInflater.inflate(R.layout.category_classify_item_related, parent, false));
} else if (viewType == VIEW_TYPE_GOODS_LIST) {//商品列表
return new GoodListViewHolder(layoutInflater.inflate(R.layout.category_classify_item_goods_list, parent, false));
} else if (viewType == VIEW_TYPE_GOODS_LIST_LABEL) {
return new GoodListLabelViewHolder(layoutInflater.inflate(R.layout.category_classify_item_goods_list_label, parent, false));
} else if (viewType == VIEW_TYPE_GOODS_LIST_MORE) {//更多
return new MoreGoodsListViewHolder(layoutInflater.inflate(R.layout.category_classify_item_more, parent, false));
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder vh, final int position) {
switch (vh.getItemViewType()) {
//热门分类
case VIEW_TYPE_HOT_SUB_CATE:
final HotSubCateViewHolder hotSubCateHolder = (HotSubCateViewHolder) vh;
int horizontalSpacing = (UJiPin.SCREEN_WIDTH - UDensity.dip2px(mContext, 16) * 2 - UDensity.dip2px(mContext, 50) * 5) / 4;
hotSubCateHolder.mGridview.setHorizontalSpacing(horizontalSpacing);
hotSubCateHolder.mGridview.setVerticalSpacing(UDensity.dip2px(mContext, 20));
final CategoryHotSubCateAdapter categoryHotSubCateAdapter = new CategoryHotSubCateAdapter(mContext, mHotSubCategoryListEntityList);
hotSubCateHolder.mGridview.setAdapter(categoryHotSubCateAdapter);
hotSubCateHolder.mGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
int hotSubViewType = categoryHotSubCateAdapter.getItemViewType(pos);
CategoryList.HotSubCategoryListEntity hotSubCategoryListEntity = mHotSubCategoryListEntityList.get(pos);
if (hotSubViewType == CategoryHotSubCateAdapter.VIEW_TYPE_HOT_SUB_CATE) {//热门分类
JumpUtils.JumpClassifyList((BaseActivity) mContext, hotSubCategoryListEntity.getLevel(), hotSubCategoryListEntity.getTag_id(), hotSubCategoryListEntity.getName());
UJPTrack.getInstance().setTrack((BaseActivity) mContext, UJPTrack.PAGE_CLASS_ + UString.urlEncode(hotSubCategoryListEntity.getName()),
"class-1-" + UString.urlEncode(hotSubCategoryListEntity.getName()));
} else if (hotSubViewType == CategoryHotSubCateAdapter.VIEW_TYPE_HOT_SUB_CATE_MORE) {//点击more
Intent intent = new Intent(mContext, CategoryPagerMoreActivity.class);
intent.putExtra(CategoryPagerMoreActivity.EXTRA_STRING_CATEGORY_NAME, mTitleName);
intent.putExtra(CategoryPagerMoreActivity.EXTRA_INT_CATEGORY_INDEX, mIndex);
intent.putExtra(CategoryPagerMoreActivity.EXTRA_STRING_CATEGORY_TAG_ID, mTagId);
mContext.startActivity(intent);
UJPTrack.getInstance().setTrack((BaseActivity) mContext,
UJPTrack.PAGE_CLASS_ + UString.urlEncode(mTitleName),
"class-1-more");
}
}
});
break;
case VIEW_TYPE_PROMOTION_LIST://banner+横滑
PromotionViewHolder promotionViewHolder = (PromotionViewHolder) vh;
final int promotionPosition = position - COUNT_HOT_SUB_CATE;
//防止recyclerview复用出现错乱的办法是有if必须有else,并且处理相反
GridLayoutManager.LayoutParams promotionLP = (GridLayoutManager.LayoutParams) promotionViewHolder.mContainer.getLayoutParams();
if (promotionPosition == 0) {//如果是第一个,则显示“相关推荐“
promotionViewHolder.mLabel.setVisibility(View.VISIBLE);
promotionLP.setMargins(-UDensity.dip2px(mContext, 5), UDensity.dip2px(mContext, 16), -UDensity.dip2px(mContext, 5), 0);
} else {
promotionViewHolder.mLabel.setVisibility(View.GONE);
promotionLP.setMargins(-UDensity.dip2px(mContext, 5), UDensity.dip2px(mContext, 4), -UDensity.dip2px(mContext, 5), 0);
}
promotionViewHolder.mContainer.setLayoutParams(promotionLP);
final CategoryList.RelatedTagListEntity relatedTagListEntity = mRelatedTagListEntityList.get(promotionPosition);
FrescoImageLoader.getInstance().load(promotionViewHolder.mCover, relatedTagListEntity.getCover());
//点击banner
promotionViewHolder.mCover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JumpUtils.JumpActivityTopic((BaseActivity) mContext, relatedTagListEntity.getName(),
relatedTagListEntity.getTag_id(), null, promotionPosition);
UJPTrack.getInstance().setTrack((BaseActivity) mContext, UJPTrack.PAGE_LABEL_ + UString.urlEncode(relatedTagListEntity.getName()),
"class-2-" + covertInt(promotionPosition + 1));
}
});
final CategoryChoiceTagAdapter adapter = new CategoryChoiceTagAdapter(mContext);
//点击横滑商品
adapter.setOnItemClickListener(new CategoryChoiceTagAdapter.OnItemClickListener() {
#Override
public void onTag4ItemClick(final CategoryList.GoodListEntity goodListEntity, int position, View view) {
Jumper.newJumper().putString(GoodsDetailActivity.EXTRA_STRING_GOODID, goodListEntity.getGoods_id() + "")
.putString(GoodsDetailActivity.EXTRA_STRING_SOURCENAME, "分类")
.putString(GoodsDetailActivity.EXTRA_STRING_SOURCEID, "活动横滑")
.jump((BaseActivity) mContext, GoodsDetailActivity.class);
UJPTrack.getInstance().setTrack((BaseActivity) mContext, UJPTrack.PAGE_GOOD + goodListEntity.getGoods_id(),
"class-2-" + covertInt(promotionPosition + 1));
}
});
promotionViewHolder.mSlideMoreRecycleView.setAdapter(adapter);
adapter.setDataRefresh(relatedTagListEntity.getGoods_list());
//横滑
promotionViewHolder.mSlideMoreRecycleView.setOnSlideTwiceLisner(new SlideMoreRecycleView.SlideTwiceLisner() {
#Override
public void onSliding(RecyclerView recyclerView) {
JumpUtils.JumpActivityTopic((BaseActivity) mContext, relatedTagListEntity.getName(),
relatedTagListEntity.getTag_id(), "", promotionPosition);
}
});
break;
case VIEW_TYPE_GOODS_LIST_LABEL://商品列表的label
break;
case VIEW_TYPE_GOODS_LIST://商品列表
int goodsListPosition = position - COUNT_HOT_SUB_CATE - mRelatedTagSize - COUNT_HOT_GOODS_LIST_LABEL;
final CategoryList.GoodListEntity goodListEntity = mGoodListEntityList.get(goodsListPosition);
final GoodListViewHolder goodsListHolder = (GoodListViewHolder) vh;
ViewCompat.setTransitionName(goodsListHolder.ivCover, mContext.getString(R.string.transition_name) + position);
goodsListHolder.rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mOnGoodsItemClickListener != null) {
mOnGoodsItemClickListener.onItemClick(goodsListHolder.rootView, goodListEntity, position, goodListEntity.getThumbnail());
}
}
});
goodsListHolder.tv_goods_selling_point.setText(goodListEntity.getSelling_point());
if (!TextUtils.isEmpty(goodListEntity.getThumbnail()))
FrescoImageLoader.getInstance().load(goodsListHolder.ivCover, goodListEntity.getThumbnail());
if (!TextUtils.isEmpty(goodListEntity.getMark())) {
goodsListHolder.ivGroupLogo.setVisibility(View.VISIBLE);
FrescoImageLoader.getInstance().load(goodsListHolder.ivGroupLogo, goodListEntity.getMark());
} else {
goodsListHolder.ivGroupLogo.setVisibility(View.GONE);
}
goodsListHolder.tvDescription.setText(goodListEntity.getGoods_name());
if (!TextUtils.isEmpty(goodListEntity.getGoods_price()))
goodsListHolder.tvPrice.setText(String.format(mContext.getString(R.string.rmb), goodListEntity.getGoods_price()));
//售罄
if (goodListEntity.getProduct_stock_total() <= 0)
goodsListHolder.ivSoldOut.setVisibility(View.VISIBLE);
else
goodsListHolder.ivSoldOut.setVisibility(View.GONE);
break;
case VIEW_TYPE_GOODS_LIST_MORE://更多推荐
MoreGoodsListViewHolder moreGoodsListViewHolder = (MoreGoodsListViewHolder) vh;
moreGoodsListViewHolder.mContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JumpUtils.JumpClassifyList((BaseActivity) mContext, mLevel, mTagId, mTitleName);
UJPTrack.getInstance().setTrack((BaseActivity) mContext, UJPTrack.PAGE_CLASS_ + UString.urlEncode(mTitleName), UJPTrack.PAGE_CLASS_CLASS + UString.urlEncode(mTitleName));
}
});
break;
}
}
#Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
}
#Override
public int getItemViewType(int position) {
if (position == 0) {
return VIEW_TYPE_HOT_SUB_CATE;
} else if (position < COUNT_HOT_SUB_CATE + mRelatedTagSize) {
return VIEW_TYPE_PROMOTION_LIST;
} else if (position < COUNT_HOT_SUB_CATE + mRelatedTagSize + COUNT_HOT_GOODS_LIST_LABEL) {
return VIEW_TYPE_GOODS_LIST_LABEL;
} else if (position < COUNT_HOT_SUB_CATE + mRelatedTagSize + COUNT_HOT_GOODS_LIST_LABEL + mGoodsListSize) {
return VIEW_TYPE_GOODS_LIST;
} else {
return VIEW_TYPE_GOODS_LIST_MORE;
}
}
#Override
public int getItemCount() {
return mGoodsListSize + mRelatedTagSize + COUNT_HOT_SUB_CATE +
COUNT_HOT_GOODS_LIST_LABEL + COUNT_HOT_GOODS_LIST_MORE;
}
//头部的热门分类
private static class HotSubCateViewHolder extends RecyclerView.ViewHolder {
private MyGridview mGridview;
HotSubCateViewHolder(View view) {
super(view);
mGridview = (MyGridview) view.findViewById(R.id.grid_view);
}
}
//banner+推荐横滑
private static class PromotionViewHolder extends RecyclerView.ViewHolder {
private SimpleDraweeView mCover;
private LinearLayout mContainer;
private TextView mLabel;
private SlideMoreRecycleView mSlideMoreRecycleView;
PromotionViewHolder(View view) {
super(view);
mContainer = (LinearLayout) view.findViewById(R.id.ll);
mLabel = (TextView) view.findViewById(R.id.label);
mCover = (SimpleDraweeView) view.findViewById(R.id.iv_cover);
mSlideMoreRecycleView = (SlideMoreRecycleView) view.findViewById(rv_tag_list);
}
}
//商品列表
private static class GoodListViewHolder extends RecyclerView.ViewHolder {
View rootView;
SimpleDraweeView ivCover;
TextView tvDescription;
TextView tvPrice;
TextView tv_goods_selling_point;
ImageView ivSoldOut;
SimpleDraweeView ivGroupLogo;
GoodListViewHolder(View v) {
super(v);
rootView = v;
ivCover = (SimpleDraweeView) v.findViewById(R.id.iv_cover);
tvDescription = (TextView) v.findViewById(R.id.tv_descrption);
tvPrice = (TextView) v.findViewById(R.id.tv_price);
tv_goods_selling_point = (TextView) v.findViewById(R.id.tv_goods_selling_point);
ivSoldOut = (ImageView) v.findViewById(R.id.iv_sold_out);
ivGroupLogo = (SimpleDraweeView) v.findViewById(R.id.iv_group_tag);
}
}
private static class GoodListLabelViewHolder extends RecyclerView.ViewHolder {
TextView mLabel;
public GoodListLabelViewHolder(View itemView) {
super(itemView);
mLabel = (TextView) itemView.findViewById(R.id.label);
}
}
private static class MoreGoodsListViewHolder extends RecyclerView.ViewHolder {
private LinearLayout mContainer;
MoreGoodsListViewHolder(View itemView) {
super(itemView);
mContainer = (LinearLayout) itemView.findViewById(R.id.container);
}
}
//点击双栏列表接口
public interface OnGoodsItemClickListener {
void onItemClick(View rootView, CategoryList.GoodListEntity goodListEntity, int position, String imageUrl);
}
public void addOnGoodsItemClickListener(OnGoodsItemClickListener listener) {
mOnGoodsItemClickListener = listener;
}
public String covertInt(int value) {
return value <= 9 ? ("0" + value) : value + "";
}
I am using recyclerview with footer everything is working fine. but i am not able to delete last item. Suppose we have 2 products in list now if user will remove one product then 1 product will remain in recyclerview then i am not able to delete that remaining product.
While i have one item it shows PACK ID null
genericViewHolder.removes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
packid=currentItem.getCart_Product_packid();
System.out.println("PACK ID"+packid);
deletetocart();
}
});
ADAPTER
public class HeaderFooterAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private static final int TYPE_FOOTER = 2;
private ArrayList<CartModel> idlistData;
private AQuery aQuery;
Context context;
public HeaderFooterAdapter(Context context,ArrayList<CartModel> idlistData) {
this.context = context;
this.idlistData = idlistData;
aQuery = new AQuery(this.context);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
if(viewType == TYPE_HEADER) {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.item_header, parent, false);
return new HeaderViewHolder (v);
} else if(viewType == TYPE_FOOTER) {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.item_footer, parent, false);
return new FooterViewHolder (v);
} else if(viewType == TYPE_ITEM) {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.listitem_buynow, parent, false);
return new GenericViewHolder (v);
}
return null;
}
private CartModel getItem (int position) {
return idlistData.get (position);
}
#Override
public void onBindViewHolder (RecyclerView.ViewHolder holder, int position) {
if(holder instanceof HeaderViewHolder) {
HeaderViewHolder headerHolder = (HeaderViewHolder) holder;
headerHolder.txtTitleHeader.setText ("Header");
headerHolder.txtTitleHeader.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick (View view) {
// Toast.makeText (context, "Clicked Header", Toast.LENGTH_SHORT).show ();
}
});
} else if(holder instanceof FooterViewHolder) {
FooterViewHolder footerHolder = (FooterViewHolder) holder;
footerHolder.txtTitleFooter.setText ("Footer");
footerHolder.FooterCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(context, "Clicked Footer", Toast.LENGTH_SHORT).show();
if(userd > 0)
{
System.out.println("Positive");
Intent intent=new Intent(BuyNowActivity.this,DelieveringProduct.class);
startActivity(intent);
}
else
{
System.out.println("Negative");
String skipsid=String.valueOf(userd);
Intent intent=new Intent(BuyNowActivity.this,Login_Page.class);
intent.putExtra("proceedtocheckoutid",skipsid);
intent.putExtra("isCheckOut",true);
startActivity(intent);
}
}
});
} else if(holder instanceof GenericViewHolder) {
final CartModel currentItem = getItem (position - 1);
final GenericViewHolder genericViewHolder = (GenericViewHolder) holder;
genericViewHolder.txtName.setText(currentItem.getCart_Product_Name());
String pics = currentItem.getCart_Product_Img();
aQuery.id(genericViewHolder.proimage).image(pics, true, true, 0, R.mipmap.ic_launcher);
genericViewHolder.buynowprice.setText("$" + currentItem.getCart_Product_Price());
genericViewHolder.buynowqtys.setText(currentItem.getCart_Product_Qty());
genericViewHolder.discounttext.setText(currentItem.getCart_Product_packDiscount());
subtotal.setText("$" + currentItem.getCart_Product_Price());
genericViewHolder.edtcoupan.setText(currentItem.getCart_Product_coupancode());
genericViewHolder.gocoupan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(genericViewHolder.edtcoupan.getText().toString().trim().length() > 0)
{
couponcode=genericViewHolder.edtcoupan.getText().toString();
packid=currentItem.getCart_Product_packid();
System.out.println("Coupan Code on click"+couponcode);
goforcoupan();
}
}
});
genericViewHolder.removes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
packid=currentItem.getCart_Product_packid();
System.out.println("PACK ID"+packid);
deletetocart();
}
});
}
#Override
public int getItemViewType (int position) {
if (isPositionHeader (position)) {
return TYPE_HEADER;
} else if(isPositionFooter (position)) {
return TYPE_FOOTER;
}
return TYPE_ITEM;
}
private boolean isPositionHeader (int position) {
return position == 0;
}
private boolean isPositionFooter (int position) {
return position == idlistData.size () + 1;
}
#Override
public int getItemCount () {
return idlistData.size () + 2;
}
class FooterViewHolder extends RecyclerView.ViewHolder {
Button FooterCheckout;
TextView txtTitleFooter;
public FooterViewHolder (View itemView) {
super (itemView);
this.txtTitleFooter = (TextView) itemView.findViewById (R.id.txtFooter);
this.FooterCheckout = (Button) itemView.findViewById (R.id.footercheckout);
}
}
class HeaderViewHolder extends RecyclerView.ViewHolder {
TextView txtTitleHeader;
public HeaderViewHolder (View itemView) {
super (itemView);
this.txtTitleHeader = (TextView) itemView.findViewById (R.id.txtHeader);
}
}
class GenericViewHolder extends RecyclerView.ViewHolder {
TextView discounttext;
LinearLayout lindiscount;
EditText edtcoupan;
TextView txtName,buynowprice,buynowqtys,buynowfreq,gocoupan,removes,firsttxt,thirdtxt;
public ImageView proimage;
public RelativeLayout linfreq,linqty;
public GenericViewHolder (View itemView) {
super (itemView);
this.txtName = (TextView) itemView.findViewById (R.id.listitem_buynow_title);
this.proimage = (ImageView)itemView.findViewById(R.id.listitem_buynow_image);
this.buynowprice = (TextView)itemView.findViewById(R.id.listitem_buynow_price);
this.buynowqtys = (TextView)itemView.findViewById(R.id.listitem_buynow_qtys);
this.buynowfreq = (TextView)itemView.findViewById(R.id.listitem_buynow_freq);
this.gocoupan = (TextView)itemView.findViewById(R.id.listitem_buynow_gocoupan);
this.edtcoupan = (EditText)itemView.findViewById(R.id.listitem_buynow_coupan);
this.removes = (TextView)itemView.findViewById(R.id.listitem_buynow_remove);
this.linfreq = (RelativeLayout)itemView.findViewById(R.id.linfreq);
this.linqty = (RelativeLayout)itemView.findViewById(R.id.linqty);
this.lindiscount = (LinearLayout)itemView.findViewById(R.id.coupancodeavailable);
this.discounttext = (TextView)itemView.findViewById(R.id.listitem_buynow_discountstring);
this.firsttxt = (TextView)itemView.findViewById(R.id.firsttext);
this.thirdtxt = (TextView)itemView.findViewById(R.id.thirdtext);
}
}
}
deletetocart
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, addtocarturl, new JSONObject(params),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
System.out.println("response -->> " + response.toString());
cartlist=new ArrayList<CartModel>();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
System.out.println("person"+person);
String responsecode = person.getString("subTotal");
System.out.println("subtot"+responsecode);
System.out.println("person"+person);
if(person.getString("responseCode").equals("1"))
{
JSONArray itemslist=person.optJSONArray("itemList");
if(itemslist==null)
{
Toast.makeText(BuyNowActivity.this, "Your Shopping Cart is Empty", Toast.LENGTH_SHORT).show();
}
else {
for (int j = 0; j < itemslist.length(); j++) {
JSONObject cartitems = itemslist.getJSONObject(j);
CartModel cvm = new CartModel();
cvm.setCart_Product_Name(cartitems.getString("prodNarration"));
cvm.setCart_Product_Price(cartitems.getString("finalPrice"));
cvm.setCart_Product_Id(cartitems.getString("productId"));
cvm.setCart_Product_Img(cartitems.getString("packLink"));
cvm.setCart_Product_Qty(cartitems.getString("qty"));
cvm.setCart_Product_packDiscount(cartitems.getString("packDIscDesc"));
cartlist.add(cvm);
}
Toast.makeText(BuyNowActivity.this, "Product Removed Successfully", Toast.LENGTH_SHORT).show();
}
}
else {
System.out.println("something wrong");
}
rcAdapter = new HeaderFooterAdapter(BuyNowActivity.this,cartlist);
rView.setAdapter(rcAdapter);
}
This is just a guess but you are not parsing your packId while re initializing your list after deleting one item.
if(person.getString("responseCode").equals("1"))
{
JSONArray itemslist=person.optJSONArray("itemList");
if(itemslist==null)
{
Toast.makeText(BuyNowActivity.this, "Your Shopping Cart is Empty", Toast.LENGTH_SHORT).show();
}
else {
for (int j = 0; j < itemslist.length(); j++) {
JSONObject cartitems = itemslist.getJSONObject(j);
CartModel cvm = new CartModel();
cvm.setCart_Product_Name(cartitems.getString("prodNarration"));
cvm.setCart_Product_Price(cartitems.getString("finalPrice"));
cvm.setCart_Product_Id(cartitems.getString("productId"));
cvm.setCart_Product_Img(cartitems.getString("packLink"));
cvm.setCart_Product_Qty(cartitems.getString("qty"));
cvm.setCart_Product_packDiscount(cartitems.getString("packDIscDesc"));
// HERE add some code for parsing packId
cartlist.add(cvm);
}
Toast.makeText(BuyNowActivity.this, "Product Removed Successfully", Toast.LENGTH_SHORT).show();
}
}
Try adding the parsing code where i have added comment.
Hope this will help you.
Below is my complete adapter class of sendbird chatting.Currently date with time is displayed with every message.viewHolder.getView("left_time") and viewHolder.getView("right_time") are views for displaying date with time and it is calculated in method getDisplayDateTime.I want date with time to be displayed only when there is a change in date.For example if there is set of messages dated 23rd june then date with time should be displayed only for the first message with date 23rd june.
I tried doing that by detecting whenever there is a change in date by storing date in xyz variable and comparing it with date of every message and whenever they are unequal then making date view of that message visible and assigning the new date to xyz variable for comparison with future messages.But this approach fails when i scroll down and scroll up list.
What is the ideal approach for achieving this?
public class SendBirdMessagingAdapter extends BaseAdapter {
private static final int TYPE_UNSUPPORTED = 0;
private static final int TYPE_MESSAGE = 1;
private static final int TYPE_SYSTEM_MESSAGE = 2;
private static final int TYPE_FILELINK = 3;
private static final int TYPE_BROADCAST_MESSAGE = 4;
private static final int TYPE_TYPING_INDICATOR = 5;
private final Context mContext;
private final LayoutInflater mInflater;
private final ArrayList<Object> mItemList;
private Hashtable<String, Long> mReadStatus;
private Hashtable<String, Long> mTypeStatus;
private List<MessagingChannel.Member> mMembers;
private long mMaxMessageTimestamp = Long.MIN_VALUE;
private long mMinMessageTimestamp = Long.MAX_VALUE;
public SendBirdMessagingAdapter(Context context) {
mContext = context;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mItemList = new ArrayList<Object>();
mReadStatus = new Hashtable<String, Long>();
mTypeStatus = new Hashtable<String, Long>();
}
#Override
public int getCount() {
return mItemList.size() + ((mTypeStatus.size() <= 0) ? 0 : 1);
}
#Override
public Object getItem(int position) {
if (position >= mItemList.size()) {
ArrayList<String> names = new ArrayList<String>();
for (MessagingChannel.Member member : mMembers) {
if (mTypeStatus.containsKey(member.getId())) {
names.add(member.getName());
}
}
return names;
}
return mItemList.get(position);
}
public void delete(Object object) {
mItemList.remove(object);
}
public void clear() {
mMaxMessageTimestamp = Long.MIN_VALUE;
mMinMessageTimestamp = Long.MAX_VALUE;
mReadStatus.clear();
mTypeStatus.clear();
mItemList.clear();
}
public void resetReadStatus(Hashtable<String, Long> readStatus) {
mReadStatus = readStatus;
}
public void setReadStatus(String userId, long timestamp) {
if (mReadStatus.get(userId) == null || mReadStatus.get(userId) < timestamp) {
mReadStatus.put(userId, timestamp);
}
}
public void setTypeStatus(String userId, long timestamp) {
if (userId.equals(SendBird.getUserId())) {
return;
}
if (timestamp <= 0) {
mTypeStatus.remove(userId);
} else {
mTypeStatus.put(userId, timestamp);
}
}
#Override
public long getItemId(int position) {
return position;
}
public void addMessageModel(MessageModel messageModel) {
if (messageModel.isPast()) {
mItemList.add(0, messageModel);
} else {
mItemList.add(messageModel);
}
updateMessageTimestamp(messageModel);
}
private void updateMessageTimestamp(MessageModel model) {
mMaxMessageTimestamp = mMaxMessageTimestamp < model.getTimestamp() ? model.getTimestamp() : mMaxMessageTimestamp;
mMinMessageTimestamp = mMinMessageTimestamp > model.getTimestamp() ? model.getTimestamp() : mMinMessageTimestamp;
}
public long getMaxMessageTimestamp() {
return mMaxMessageTimestamp == Long.MIN_VALUE ? Long.MAX_VALUE : mMaxMessageTimestamp;
}
public long getMinMessageTimestamp() {
return mMinMessageTimestamp == Long.MAX_VALUE ? Long.MIN_VALUE : mMinMessageTimestamp;
}
public void setMembers(List<MessagingChannel.Member> members) {
mMembers = members;
}
#Override
public int getItemViewType(int position) {
if (position >= mItemList.size()) {
return TYPE_TYPING_INDICATOR;
}
Object item = mItemList.get(position);
if (item instanceof Message) {
return TYPE_MESSAGE;
} else if (item instanceof FileLink) {
return TYPE_FILELINK;
} else if (item instanceof SystemMessage) {
return TYPE_SYSTEM_MESSAGE;
} else if (item instanceof BroadcastMessage) {
return TYPE_BROADCAST_MESSAGE;
}
return TYPE_UNSUPPORTED;
}
#Override
public int getViewTypeCount() {
return 6;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
final Object item = getItem(position);
if (convertView == null || ((ViewHolder) convertView.getTag()).getViewType() != getItemViewType(position)) {
viewHolder = new ViewHolder();
viewHolder.setViewType(getItemViewType(position));
switch (getItemViewType(position)) {
case TYPE_UNSUPPORTED:
convertView = new View(mInflater.getContext());
convertView.setTag(viewHolder);
break;
case TYPE_MESSAGE: {
TextView tv;
CircularImageView iv;
View v;
convertView = mInflater.inflate(R.layout.sendbird_view_messaging_message, parent, false);
v = convertView.findViewById(R.id.left_container);
viewHolder.setView("left_container", v);
iv = (CircularImageView) convertView.findViewById(R.id.img_left_thumbnail);
viewHolder.setView("left_thumbnail", iv);
tv = (TextView) convertView.findViewById(R.id.txt_left);
viewHolder.setView("left_message", tv);
tv = (TextView) convertView.findViewById(R.id.txt_left_name);
viewHolder.setView("left_name", tv);
tv = (TextView) convertView.findViewById(R.id.txt_left_time);
viewHolder.setView("left_time", tv);
v = convertView.findViewById(R.id.right_container);
viewHolder.setView("right_container", v);
iv = (CircularImageView) convertView.findViewById(R.id.img_right_thumbnail);
viewHolder.setView("right_thumbnail", iv);
tv = (TextView) convertView.findViewById(R.id.txt_right);
viewHolder.setView("right_message", tv);
tv = (TextView) convertView.findViewById(R.id.txt_right_name);
viewHolder.setView("right_name", tv);
tv = (TextView) convertView.findViewById(R.id.txt_right_time);
viewHolder.setView("right_time", tv);
tv = (TextView) convertView.findViewById(R.id.txt_right_status);
viewHolder.setView("right_status", tv);
convertView.setTag(viewHolder);
break;
}
case TYPE_SYSTEM_MESSAGE: {
convertView = mInflater.inflate(R.layout.sendbird_view_system_message, parent, false);
viewHolder.setView("message", convertView.findViewById(R.id.txt_message));
convertView.setTag(viewHolder);
break;
}
case TYPE_BROADCAST_MESSAGE: {
convertView = mInflater.inflate(R.layout.sendbird_view_system_message, parent, false);
viewHolder.setView("message", convertView.findViewById(R.id.txt_message));
convertView.setTag(viewHolder);
break;
}
case TYPE_FILELINK: {
TextView tv;
CircularImageView civ;
ImageView iv;
View v;
convertView = mInflater.inflate(R.layout.sendbird_view_messaging_filelink, parent, false);
v = convertView.findViewById(R.id.left_container);
viewHolder.setView("left_container", v);
civ = (CircularImageView) convertView.findViewById(R.id.img_left_thumbnail);
viewHolder.setView("left_thumbnail", civ);
iv = (ImageView) convertView.findViewById(R.id.img_left);
viewHolder.setView("left_image", iv);
tv = (TextView) convertView.findViewById(R.id.txt_left_name);
viewHolder.setView("left_name", tv);
tv = (TextView) convertView.findViewById(R.id.txt_left_time);
viewHolder.setView("left_time", tv);
v = convertView.findViewById(R.id.right_container);
viewHolder.setView("right_container", v);
civ = (CircularImageView) convertView.findViewById(R.id.img_right_thumbnail);
viewHolder.setView("right_thumbnail", civ);
iv = (ImageView) convertView.findViewById(R.id.img_right);
viewHolder.setView("right_image", iv);
tv = (TextView) convertView.findViewById(R.id.txt_right_name);
viewHolder.setView("right_name", tv);
tv = (TextView) convertView.findViewById(R.id.txt_right_time);
viewHolder.setView("right_time", tv);
tv = (TextView) convertView.findViewById(R.id.txt_right_status);
viewHolder.setView("right_status", tv);
convertView.setTag(viewHolder);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(mContext)
.setTitle("Foodvite")
.setMessage("Do you want to download this file?")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
downloadUrl((FileLink) item, mContext);
} catch (IOException e) {
e.printStackTrace();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create()
.show();
}
});
break;
}
case TYPE_TYPING_INDICATOR: {
convertView = mInflater.inflate(R.layout.sendbird_view_typing_indicator, parent, false);
viewHolder.setView("message", convertView.findViewById(R.id.txt_message));
convertView.setTag(viewHolder);
break;
}
}
}
viewHolder = (ViewHolder) convertView.getTag();
switch (getItemViewType(position)) {
case TYPE_UNSUPPORTED:
break;
case TYPE_MESSAGE:
Message message = (Message) item;
if (message.getSenderId().equals(SendBird.getUserId())) {
viewHolder.getView("left_container", View.class).setVisibility(View.GONE);
viewHolder.getView("right_container", View.class).setVisibility(View.VISIBLE);
displayUrlImage(viewHolder.getView("right_thumbnail", CircularImageView.class), message.getSenderImageUrl(), true);
viewHolder.getView("right_name", TextView.class).setText(message.getSenderName());
viewHolder.getView("right_message", TextView.class).setText(message.getMessage());
viewHolder.getView("right_time", TextView.class).setText(getDisplayDateTime(mContext, message.getTimestamp()));
int readCount = 0;
for (String key : mReadStatus.keySet()) {
if (key.equals(message.getSenderId())) {
readCount += 1;
continue;
}
if (mReadStatus.get(key) >= message.getTimestamp()) {
readCount += 1;
}
}
if (readCount < mReadStatus.size()) {
if (mReadStatus.size() - readCount > 1) {
viewHolder.getView("right_status", TextView.class).setText("Unread " + (mReadStatus.size() - readCount));
} else {
viewHolder.getView("right_status", TextView.class).setText("Unread");
}
} else {
viewHolder.getView("right_status", TextView.class).setText("");
}
viewHolder.getView("right_container").setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
new AlertDialog.Builder(mContext)
.setTitle("Foodvite")
.setMessage("Do you want to delete a message?")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SendBird.deleteMessage(((Message) item).getMessageId(), new DeleteMessageHandler() {
#Override
public void onError(SendBirdException e) {
e.printStackTrace();
}
#Override
public void onSuccess(long messageId) {
mSendBirdMessagingAdapter.delete(item);
mSendBirdMessagingAdapter.notifyDataSetChanged();
Toast.makeText(mContext, "Message has been deleted.", Toast.LENGTH_SHORT).show();
}
});
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create()
.show();
return true;
}
});
} else {
viewHolder.getView("left_container", View.class).setVisibility(View.VISIBLE);
viewHolder.getView("right_container", View.class).setVisibility(View.GONE);
displayUrlImage(viewHolder.getView("left_thumbnail", CircularImageView.class), message.getSenderImageUrl(), true);
viewHolder.getView("left_name", TextView.class).setText(message.getSenderName());
viewHolder.getView("left_message", TextView.class).setText(message.getMessage());
viewHolder.getView("left_time", TextView.class).setText(getDisplayDateTime(mContext, message.getTimestamp()));
if(isGroupChat)
viewHolder.getView("left_name", TextView.class).setVisibility(View.VISIBLE);
else
viewHolder.getView("left_name", TextView.class).setVisibility(View.GONE);
}
break;
case TYPE_SYSTEM_MESSAGE:
SystemMessage systemMessage = (SystemMessage) item;
viewHolder.getView("message", TextView.class).setText(Html.fromHtml(systemMessage.getMessage()));
break;
case TYPE_BROADCAST_MESSAGE:
BroadcastMessage broadcastMessage = (BroadcastMessage) item;
viewHolder.getView("message", TextView.class).setText(Html.fromHtml(broadcastMessage.getMessage()));
break;
case TYPE_FILELINK:
FileLink fileLink = (FileLink) item;
if (fileLink.getSenderId().equals(SendBird.getUserId())) {
viewHolder.getView("left_container", View.class).setVisibility(View.GONE);
viewHolder.getView("right_container", View.class).setVisibility(View.VISIBLE);
displayUrlImage(viewHolder.getView("right_thumbnail", ImageView.class), fileLink.getSenderImageUrl(), true);
viewHolder.getView("right_name", TextView.class).setText(fileLink.getSenderName());
if (fileLink.getFileInfo().getType().toLowerCase().startsWith("image")) {
displayUrlImage(viewHolder.getView("right_image", ImageView.class), fileLink.getFileInfo().getUrl());
} else {
viewHolder.getView("right_image", CircularImageView.class).setImageResource(R.drawable.sendbird_icon_file);
}
viewHolder.getView("right_time", TextView.class).setText(getDisplayDateTime(mContext, fileLink.getTimestamp()));
int readCount = 0;
for (String key : mReadStatus.keySet()) {
if (key.equals(fileLink.getSenderId())) {
continue;
}
if (mReadStatus.get(key) < fileLink.getTimestamp()) {
readCount += 1;
}
}
if (readCount < mReadStatus.size() - 1) {
viewHolder.getView("right_status", TextView.class).setText("Unread");
} else {
viewHolder.getView("right_status", TextView.class).setText("");
}
} else {
viewHolder.getView("left_container", View.class).setVisibility(View.VISIBLE);
viewHolder.getView("right_container", View.class).setVisibility(View.GONE);
displayUrlImage(viewHolder.getView("left_thumbnail", ImageView.class), fileLink.getSenderImageUrl(), true);
viewHolder.getView("left_name", TextView.class).setText(fileLink.getSenderName());
if (fileLink.getFileInfo().getType().toLowerCase().startsWith("image")) {
displayUrlImage(viewHolder.getView("left_image", ImageView.class), fileLink.getFileInfo().getUrl());
} else {
viewHolder.getView("left_image", CircularImageView.class).setImageResource(R.drawable.sendbird_icon_file);
}
if(isGroupChat)
viewHolder.getView("left_name", TextView.class).setVisibility(View.VISIBLE);
else
viewHolder.getView("left_name", TextView.class).setVisibility(View.GONE);
viewHolder.getView("left_time", TextView.class).setText(getDisplayDateTime(mContext, fileLink.getTimestamp()));
}
break;
case TYPE_TYPING_INDICATOR: {
int itemCount = ((List) item).size();
String typeMsg = ((List) item).get(0)
+ ((itemCount > 1) ? " +" + (itemCount - 1) : "")
+ ((itemCount > 1) ? " are " : " is ")
+ "typing...";
viewHolder.getView("message", TextView.class).setText(typeMsg);
break;
}
}
return convertView;
}
public boolean checkTypeStatus() {
/**
* Clear an old type status.
*/
for (String key : mTypeStatus.keySet()) {
Long ts = mTypeStatus.get(key);
if (System.currentTimeMillis() - ts > 10 * 1000L) {
mTypeStatus.remove(key);
return true;
}
}
return false;
}
private class ViewHolder {
private Hashtable<String, View> holder = new Hashtable<String, View>();
private int type;
public int getViewType() {
return this.type;
}
public void setViewType(int type) {
this.type = type;
}
public void setView(String k, View v) {
holder.put(k, v);
}
public View getView(String k) {
return holder.get(k);
}
public <T> T getView(String k, Class<T> type) {
return type.cast(getView(k));
}
}
}
private static String getDisplayDateTime(Context context, long milli) {
Date date = new Date(milli);
if (System.currentTimeMillis() - milli < 60 * 60 * 24 * 1000l) {
return DateFormat.getTimeFormat(context).format(date);
}
return DateFormat.getDateFormat(context).format(date) + " " + DateFormat.getTimeFormat(context).format(date);
}
Try below code for your method,
private static String getDisplayDateTime(Context context, long milli, long milli2)
{
Date date = new Date(milli);
Date previousDate = new Date(milli2);
String strCurrentDate = "", strPreviousDate = "";
if (System.currentTimeMillis() - milli < 60 * 60 * 24 * 1000l)
{
strCurrentDate = DateFormat.getTimeFormat(context).format(date);
if(milli2 != -1)
strPreviousDate = DateFormat.getTimeFormat(context).format(previousDate);
//return strCurrentDate.equals(strPreviousDate) ? "" : strCurrentDate;
}
else
{
strCurrentDate = DateFormat.getDateFormat(context).format(date) + " " + DateFormat.getTimeFormat(context).format(date);
if(milli2 != -1)
strPreviousDate = DateFormat.getDateFormat(context).format(strPreviousDate) + " " + DateFormat.getTimeFormat(context).format(strPreviousDate);
}
return strCurrentDate.equals(strPreviousDate) ? "" : strCurrentDate;
}
Now call your methods like below
if(position > 0)
{
final Object previousItem = getItem(position - 1);
Message previousMessage = (Message) previousItem;
viewHolder.getView("right_time", TextView.class).setText(getDisplayDateTime(mContext, message.getTimestamp(), previousMessage.getTimestamp()));
}
else
{
viewHolder.getView("right_time", TextView.class).setText(getDisplayDateTime(mContext, message.getTimestamp(), -1));
}
I had a similar problem (ref this SO Question) few months ago and nothing worked except extending from ArrayAdapter<MyObject> instead of BaseAdapter.
So, change the base class of your adapter to ArrayAdapter<MyObject> and implement the prompted method of the abstract class. you might need to move some you your existing code to these overridden methods for better performance.
You can force the system to redraw all items by calling BaseAdapter.notifyDataSetChanged()
The problem is that when i stretch up the pullToRefreshLiew (similar to listview), the memory the application occupy will be increasing step by step. I have tried many methods from the internet, but the bug still exists.
When i stretch up the pullToRefreshLiew, the memory will increasing to 90m
from 50m gradually.
Here is my memory monitor:
Here is my code below: (I omit the import code)
if you need my xml code,i will paste them as well.I am very grateful to you for your help.
public class YuerjingActivity extends CommonActivity implements View.OnClickListener {
private RelativeLayout back;
private int baseid;
private PullToRefreshListView pullToRefreshListView;
private ArrayList<ForumListItem> forumListItems = new ArrayList<ForumListItem>();
private MyAdapter myAdapter;
private LinearLayout noTip;
private RelativeLayout postForum;
static class ViewHolder1 {
TextView title;
TextView line;
}
static class ViewHolder2 {
private ImageView avatar;
private TextView name;
private TextView time;
private ImageView huo;
private ImageView jing;
private TextView title;
private LinearLayout pics;
private ImageView img1;
private ImageView img2;
private ImageView img3;
private ImageView img4;
private TextView replynum;
}
protected class MyAdapter extends BaseAdapter {
public MyAdapter() {
}
public int getCount() {
return forumListItems.size();
}
public View getView(final int position, View convertView, ViewGroup viewGroup) {
int t = getItemViewType(position);
ViewHolder1 viewHolder1 = null;
ViewHolder2 viewHolder2 = null;
ForumListItem forumListItem = forumListItems.get(position);
if (convertView == null) {
if (t == 1) {
convertView = getLayoutInflater().inflate(R.layout.item_top, null);
viewHolder1 = new ViewHolder1();
viewHolder1.title = (TextView) convertView.findViewById(R.id.title);
viewHolder1.line = (TextView) convertView.findViewById(R.id.top_line);
convertView.setTag(viewHolder1);
} else {
convertView = getLayoutInflater().inflate(R.layout.common_forum_item, null);
viewHolder2 = new ViewHolder2();
viewHolder2.avatar = (ImageView) convertView.findViewById(R.id.avatar);
viewHolder2.name = (TextView) convertView.findViewById(R.id.name);
viewHolder2.time = (TextView) convertView.findViewById(R.id.time);
viewHolder2.jing = (ImageView) convertView.findViewById(R.id.jing);
viewHolder2.huo = (ImageView) convertView.findViewById(R.id.huo);
viewHolder2.pics = (LinearLayout) convertView.findViewById(R.id.pics);
viewHolder2.img1 = (ImageView) convertView.findViewById(R.id.img1);
viewHolder2.img2 = (ImageView) convertView.findViewById(R.id.img2);
viewHolder2.img3 = (ImageView) convertView.findViewById(R.id.img3);
viewHolder2.img4 = (ImageView) convertView.findViewById(R.id.img4);
viewHolder2.replynum = (TextView) convertView.findViewById(R.id.replynum);
viewHolder2.title = (TextView) convertView.findViewById(R.id.title);
convertView.setTag(viewHolder2);
}
} else {
if (t == 1) {
viewHolder1 = (ViewHolder1) convertView.getTag();
} else {
viewHolder2 = (ViewHolder2) convertView.getTag();
}
}
if (t == 1) {
viewHolder1.title.setText(forumListItem.getTitle());
if (position + 1 < getCount()) {
if (forumListItems.get(position + 1).getIs_top() == 0) {
viewHolder1.line.setVisibility(View.VISIBLE);
} else {
viewHolder1.line.setVisibility(View.GONE);
}
} else {
viewHolder1.line.setVisibility(View.GONE);
}
} else {
if (forumListItem.getAvatar() == null) {
viewHolder2.avatar.setImageResource(R.drawable.user);
} else {
ImageLoader.getInstance().displayImage(forumListItem.getAvatar(), viewHolder2.avatar, UIL.getOption3());
}
viewHolder2.name.setText(forumListItem.getName());
viewHolder2.time.setText(DateUtils.toNow(forumListItem.getTime()));
viewHolder2.title.setText(forumListItem.getTitle());
if (forumListItem.getIs_hot() == 1) {
viewHolder2.huo.setVisibility(View.VISIBLE);
} else {
viewHolder2.huo.setVisibility(View.GONE);
}
if (forumListItem.getIs_rec() == 1) {
viewHolder2.jing.setVisibility(View.VISIBLE);
} else {
viewHolder2.jing.setVisibility(View.GONE);
}
viewHolder2.replynum.setText(forumListItem.getReplynum());
viewHolder2.img1.setVisibility(View.GONE);
viewHolder2.img2.setVisibility(View.GONE);
viewHolder2.img3.setVisibility(View.GONE);
viewHolder2.img4.setVisibility(View.GONE);
for (int i = 0; i < forumListItem.pics.size(); i++) {
if (i == 0) {
viewHolder2.pics.setVisibility(View.VISIBLE);
ImageLoader.getInstance().displayImage(forumListItem.pics.get(i), viewHolder2.img1, UIL.getOptions(R.drawable.info_head));
viewHolder2.img1.setVisibility(View.VISIBLE);
}
if (i == 1) {
ImageLoader.getInstance().displayImage(forumListItem.pics.get(i), viewHolder2.img2, UIL.getOptions(R.drawable.info_head));
viewHolder2.img2.setVisibility(View.VISIBLE);
}
if (i == 2) {
ImageLoader.getInstance().displayImage(forumListItem.pics.get(i), viewHolder2.img3, UIL.getOptions(R.drawable.info_head));
viewHolder2.img3.setVisibility(View.VISIBLE);
}
if (i == 3) {
ImageLoader.getInstance().displayImage(forumListItem.pics.get(i), viewHolder2.img4, UIL.getOptions(R.drawable.info_head));
viewHolder2.img4.setVisibility(View.VISIBLE);
}
}
}
return convertView;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return forumListItems.get(position).getIs_top();
}
}
private static class ForumListItem {
private String avatar;
private String name;
private String time;
private int is_hot;
private int is_rec;
private int has_pic;
private int is_top;
private String title;
private String replynum;
private int id;
public ArrayList<String> pics = new ArrayList<String>();
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public int getIs_top() {
return is_top;
}
public void setIs_top(int is_top) {
this.is_top = is_top;
}
public int getHas_pic() {
return has_pic;
}
public void setHas_pic(int has_pic) {
this.has_pic = has_pic;
}
public int getIs_rec() {
return is_rec;
}
public void setIs_rec(int is_rec) {
this.is_rec = is_rec;
}
public int getIs_hot() {
return is_hot;
}
public void setIs_hot(int is_hot) {
this.is_hot = is_hot;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getReplynum() {
return replynum;
}
public void setReplynum(String replynum) {
this.replynum = replynum;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yuerjing);
init();
}
private void init() {
back = generateFindViewById(R.id.back);
back.setOnClickListener(this);
baseid = 0;
noTip = generateFindViewById(R.id.notip);
pullToRefreshListView = generateFindViewById(R.id.quanzi);
myAdapter = new MyAdapter();
pullToRefreshListView.setAdapter(myAdapter);
pullToRefreshListView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));
pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
pullToRefreshListView.setOnRefreshListener(new MyOnRefreshListener2());
pullToRefreshListView.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (HttpUtil.isNetworkConnected(getApplicationContext())) {
Intent intent = new Intent(YuerjingActivity.this, NewForumActivity.class);
intent.putExtra("postid", forumListItems.get(position - 1).getId());
startActivity(intent);
} else {
}
}
});
postForum = generateFindViewById(R.id.xiexie);
postForum.setOnClickListener(this);
getList("new");
}
class MyOnRefreshListener2 implements PullToRefreshBase.OnRefreshListener2<ListView> {
public MyOnRefreshListener2() {
}
#Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
getList("new");
}
#Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
getList("old");
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
}
}
private void getList(final String dir) {
if (HttpUtil.isNetworkConnected(getApplicationContext())) {
RequestQueue m_queue = Volley.newRequestQueue(getApplicationContext());
JSONObject object = new JSONObject();
String param = "";
String url = "";
try {
if (UserInfo.getInstance().getHaslogin(getApplicationContext()) == -1 || UserInfo.getInstance().getHaslogin(getApplicationContext()) == 0) {
object.put("uid", 0);
} else {
object.put("uid", UserInfo.getInstance().getUserId(getApplicationContext()));
object.put("token", UserInfo.getInstance().getAccessToken(getApplicationContext()));
}
object.put("utype", 1);
object.put("posttype", "2");
object.put("classid", "0");
object.put("pagesize", 10);
object.put("dir", dir);
if (!dir.equals("new")) {
object.put("baseid", baseid);
}
param = object.toString();
url = Rpc.m_rpc_url + "&message=" + "USER_GET_ARTICLES3" + "&data=" + java.net.URLEncoder.encode(param, "utf-8");
System.err.println(url);
System.err.println(baseid);
} catch (Exception e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String result = response.toString();
JSONObject indexData = Utils.getInfoJsonObject(result);
boolean flag = indexData.getBoolean("ret");
int flagCode = indexData.getInt("retCode");
if (!flag) {
} else {
if (flagCode == 1) {
if (dir.equals("new")) {
forumListItems.clear();
baseid = 0;
}
String avatar_header = indexData.getString("avatar_header");
JSONArray jsonArray = indexData.getJSONArray("posts");
for (int i = 0; i < jsonArray.length(); i++) {
ForumListItem forumListItem = new ForumListItem();
if (jsonArray.getJSONObject(i).getString("author_avatar").equals("null") || jsonArray.getJSONObject(i).getString("author_avatar") == null) {
forumListItem.setAvatar(null);
} else {
forumListItem.setAvatar(avatar_header + jsonArray.getJSONObject(i).getString("author_avatar"));
}
forumListItem.setName(jsonArray.getJSONObject(i).getString("author_name"));
forumListItem.setTime(jsonArray.getJSONObject(i).getString("post_time"));
forumListItem.setReplynum(jsonArray.getJSONObject(i).getString("replynum"));
forumListItem.setTitle(jsonArray.getJSONObject(i).getString("title"));
forumListItem.setId(jsonArray.getJSONObject(i).getInt("id"));
if (jsonArray.getJSONObject(i).getInt("is_hot") == 1) {
forumListItem.setIs_hot(1);
} else {
forumListItem.setIs_hot(0);
}
if (jsonArray.getJSONObject(i).getInt("has_pic") == 1) {
forumListItem.setHas_pic(1);
} else {
forumListItem.setHas_pic(0);
}
if (jsonArray.getJSONObject(i).getInt("is_rec") == 1) {
forumListItem.setIs_rec(1);
} else {
forumListItem.setIs_rec(0);
}
if (jsonArray.getJSONObject(i).getInt("is_top") == 1) {
forumListItem.setIs_top(1);
} else {
forumListItem.setIs_top(0);
}
if (forumListItem.getHas_pic() == 1 && jsonArray.getJSONObject(i).has("pics")) {
JSONArray pics = jsonArray.getJSONObject(i).getJSONArray("pics");
for (int j = 0; j < pics.length(); j++) {
forumListItem.pics.add(avatar_header + pics.getJSONObject(j).getString("srcurl"));
}
}
forumListItems.add(forumListItem);
}
}else {
Toast.makeText(getApplicationContext(), "retCode=" + flagCode, Toast.LENGTH_SHORT).show();
}
myAdapter.notifyDataSetChanged();
pullToRefreshListView.onRefreshComplete();
if (forumListItems.size() > 0 && forumListItems.get(forumListItems.size() - 1).getIs_top() == 0) {
baseid = forumListItems.get(forumListItems.size() - 1).getId();
} else {
baseid = 0;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pullToRefreshListView.onRefreshComplete();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(5000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
m_queue.add(jsonObjectRequest);
m_queue.start();
} else {
pullToRefreshListView.postDelayed(new Runnable() {
#Override
public void run() {
pullToRefreshListView.onRefreshComplete();
}
}, 500);
}
}
}