Recyclerview with footer not able to delete last item - android

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.

Related

findLastVisibleItemPosition() returns -1

Create an adapter object, find recycler view id to set adapter and then set layout manager. In scroll listener, unable to get correct LastVisibleItemPosition, it return -1 to me. findFirstVisibleItemPosition() also returning -1.
//Here is Adapter
public class CategoryProduct extends RecyclerView.Adapter<RecyclerView.ViewHolder>
`enter code here`{
private static final int ITEM = 0;
private static final int LOADING = 1;
public String vertical = "";
Context context;
private boolean isLoadingAdded = false;
private boolean retryPageLoad = false;
private List<com.example.it.camanagement.model.CategoryProduct> dataSet;
public CategoryProduct(ArrayList<com.example.it.camanagement.model.CategoryProduct> data, Context context, String vertical) {
this.dataSet = data;
this.context = context;
this.vertical = vertical;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case ITEM:
View viewLoading;
if (vertical.equals("vertical")) {
viewLoading = LayoutInflater.from(parent.getContext())
.inflate(R.layout.category_product_list, parent, false);
} else {
viewLoading = LayoutInflater.from(parent.getContext())
.inflate(R.layout.category_product_list_grid, parent, false);
}
viewHolder = new MyViewHolder(viewLoading);
break;
case LOADING:
View viewLoading1 = inflater.inflate(R.layout.item_progress, parent, false);
viewHolder = new LoadingVH(viewLoading1);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int listPosition) {
if (listPosition == dataSet.size() - 1) {
CategoryDetails categoryDetails = (CategoryDetails) context;
categoryDetails.onBottomReached(listPosition);
}
switch (getItemViewType(listPosition)) {
case ITEM:
final MyViewHolder myViewHolder = (MyViewHolder) holder;
TextView textViewName = myViewHolder.productName;
// TextView textViewVersion = holder.textViewVersion;
ImageView imageView = myViewHolder.productImage;
RatingBar productRating = myViewHolder.productRasting;
TextView productCost = myViewHolder.productCost;
TextView productDiscount = myViewHolder.productDistCount;
TextView productCOLOR = myViewHolder.productColor;
TextView productId = myViewHolder.product_id;
TextView productModel = myViewHolder.productModel;
TextView productQuantity = myViewHolder.productQuantity;
productModel.setText(dataSet.get(listPosition).getModel());
productQuantity.setText(dataSet.get(listPosition).getQuantity());
productId.setText(dataSet.get(listPosition).getProduct_id());
textViewName.setText(dataSet.get(listPosition).getName());
Glide.with(context).load(dataSet.get(listPosition).getImage()).into(imageView);
productRating.setRating(Float.parseFloat(String.valueOf(dataSet.get(listPosition).getRating())));
productCost.setText("RM " + dataSet.get(listPosition).getPrice());
productDiscount.setText(dataSet.get(listPosition).getDiscount());
if (dataSet.get(listPosition).getSpecial().trim().length() != 0) {
myViewHolder.special.setText("RM " + dataSet.get(listPosition).getSpecial());
strikeThroughText(productCost);
}
break;
case LOADING:
LoadingVH loadingVH = (LoadingVH) holder;
if (retryPageLoad) {
loadingVH.mErrorLayout.setVisibility(View.VISIBLE);
loadingVH.mProgressBar.setVisibility(View.GONE);
loadingVH.mErrorTxt.setText(
errorMsg != null ?
errorMsg :
context.getString(R.string.error_msg_unknown));
} else {
loadingVH.mErrorLayout.setVisibility(View.GONE);
loadingVH.mProgressBar.setVisibility(View.VISIBLE);
}
break;
}
}
private void strikeThroughText(TextView price) {
price.setPaintFlags(price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
#Override
public int getItemCount() {
return dataSet == null ? 0 : dataSet.size();
//return dataSet.size();
}
#Override
public int getItemViewType(int position) {
return (position == dataSet.size() - 1 && isLoadingAdded) ? LOADING : ITEM;
}
public com.example.it.camanagement.model.CategoryProduct getItem(int position) {
return dataSet.get(position);
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView productName, productColor, productCost, productDistCount, product_id, productModel, productQuantity, special;
RatingBar productRasting;
ImageView productImage;
public MyViewHolder(View itemView) {
super(itemView);
this.productName = (TextView) itemView.findViewById(R.id.product_name);
this.productColor = (TextView) itemView.findViewById(R.id.product_color);
this.productCost = (TextView) itemView.findViewById(R.id.cost);
this.productDistCount = (TextView) itemView.findViewById(R.id.discount);
this.productRasting = (RatingBar) itemView.findViewById(R.id.product_rating);
this.product_id = (TextView) itemView.findViewById(R.id.product_iid);
this.productQuantity = (TextView) itemView.findViewById(R.id.quantity);
this.productModel = (TextView) itemView.findViewById(R.id.modelProduct);
//this.textViewVersion = (TextView) itemView.findViewById(R.id.textViewVersion);
this.productImage = (ImageView) itemView.findViewById(R.id.product_image);
this.special = (TextView) itemView.findViewById(R.id.special);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent i = new Intent(context, ProductDescription.class);
i.putExtra("productName", ((TextView) v.findViewById(R.id.product_name)).getText().toString());
i.putExtra("product_id", ((TextView) v.findViewById(R.id.product_iid)).getText().toString());
context.startActivity(i);
if (getPosition() == 0) {
// Toast.makeText(v.getContext(), " On CLick one", Toast.LENGTH_SHORT).show();
}
if (getPosition() == 1) {
//Toast.makeText(v.getContext(), " On CLick Two", Toast.LENGTH_SHORT).show();
}
if (getPosition() == 2) {
// Toast.makeText(v.getContext(), " On CLick Three", Toast.LENGTH_SHORT).show();
}
if (getPosition() == 3) {//
// Toast.makeText(v.getContext(), " On CLick Fore", Toast.LENGTH_SHORT).show();
}
}
});
}
}
protected class LoadingVH extends RecyclerView.ViewHolder {
private ProgressBar mProgressBar;
private ImageButton mRetryBtn;
private TextView mErrorTxt;
private LinearLayout mErrorLayout;
public LoadingVH(View itemView) {
super(itemView);
mProgressBar = (ProgressBar) itemView.findViewById(R.id.loadmore_progress);
mRetryBtn = (ImageButton) itemView.findViewById(R.id.loadmore_retry);
mErrorTxt = (TextView) itemView.findViewById(R.id.loadmore_errortxt);
mErrorLayout = (LinearLayout) itemView.findViewById(R.id.loadmore_errorlayout);
}
}
}
//Recycler View
categoryProduct = (RecyclerView) findViewById(R.id.categoryProductList);
categoryProductAdapter = new CategoryProduct(categoryProduct,categoryProductList, context);
categoryProduct.setAdapter(categoryProductAdapter);
categoryProduct.setNestedScrollingEnabled(false);
categoryProduct.setHasFixedSize(false);
girdLayoutManager = new GridLayoutManager(CategoryDetails.this, 2);
categoryProduct.setLayoutManager(girdLayoutManager);
//scroll Listener
scrollListener = new EndlessRecyclerViewScrollListener(girdLayoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to the bottom of the list
Log.d("pageCount", "" + page);
Log.d("FirstVisibleITEM", "" + girdLayoutManager.findFirstVisibleItemPosition());
Log.d("LastVisibleITEM", "" + girdLayoutManager.findLastVisibleItemPosition());
}
};
categoryProduct.addOnScrollListener(scrollListener);
Finally solved it, Issue was: I was creating the object of layout manager two times. one in method(API response received and after notify the adapter) and another one in OnCreate() method of activity. after removing one object from method( API response received and after notify the adapter), fixed the issue.

scroll recyclerview after click item of another recyclerview?

I want to scroll recyclerview by click on category position of another recyclerview which is called in popup menu...Below is my code, I am using Sectional Recyclerview and i want to get section item position while click on second recyclerview item...Please note that both recyclerview item's category id is same;
CategoryMenuRecyclerview Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<MenuItem.ProductCategory> mDataset;
private ItemListner itemListner;
RestaurantMenuActivity mContext;
public MyAdapter(RestaurantMenuActivity mContext, ArrayList<MenuItem.ProductCategory> productList, ItemListner itemListner) {
mDataset = productList;
this.itemListner = itemListner;
this.mContext = mContext;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public View mainView;
TextView tvCategory, tvCategoryNo;
public ViewHolder(View v) {
super(v);
mainView = v;
tvCategory = (TextView) v.findViewById(R.id.tvCategory);
tvCategoryNo = (TextView) v.findViewById(R.id.tvCategoryNo);
}
}
// Create new views (invoked by the layout manager)
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.tvCategory.setText(mDataset.get(position).getCategoryName());
holder.mainView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemListner.Item(position);
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
}
and i want to scroll below adapter with click item of upper recyclerview item;
RestaurantMenuAdapter;
public class RestaurantMenuAdapter extends SectionedRecyclerViewAdapter<RecyclerView.ViewHolder> {
private List<MenuItem.ProductCategory> allData;
public RestaurantMenuAdapter(List<MenuItem.ProductCategory> data) {
this.allData = data;
}
#Override
public int getSectionCount() {
return allData == null ? 0 : allData.size();
}
private MenuItem.ProductCategory getItem(int position) {
return allData.get(position);
}
#Override
public int getItemCount(int section) {
return allData.get(section).getProductDetails() == null ? 0 : allData.get(section).getProductDetails().size();
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int section) {
String sectionName = allData.get(section).getCategoryName();
SectionViewHolder sectionViewHolder = (SectionViewHolder) holder;
sectionViewHolder.tvCategory.setText(sectionName);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int section, final int relativePosition, int absolutePosition) {
final ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
itemViewHolder.tvProductName.setText(allData.get(section).getProductDetails().get(relativePosition).getProductName());
itemViewHolder.tvDescription.setText("Grass Fed Beef with creespy bacon, tasty cheese, salad, relish and hot");
itemViewHolder.tvPrice.setText("$ " + allData.get(section).getProductDetails().get(relativePosition).getCurrentPrice());
if (near_by_restaurant) {
rlAddCart.setVisibility(View.VISIBLE);
if (tvCategoryCount.getText().toString().matches("0")) {
rlAddCart.setVisibility(View.GONE);
} else {
rlAddCart.setVisibility(View.VISIBLE);
}
if (allData.get(section).getProductDetails().get(relativePosition).getIsOpen().equalsIgnoreCase("1")) {
itemViewHolder.ll_product.setAlpha(0.5f);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(RestaurantMenuActivity.this)
.setMessage("Sorry kitchen is closed")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
});
} else if (allData.get(section).getProductDetails().get(relativePosition).getIsSoldout().equalsIgnoreCase("1")) {
itemViewHolder.tvSoldOut.setVisibility(View.VISIBLE);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(RestaurantMenuActivity.this)
.setMessage("Sorry all items are sold out")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Your code
dialog.dismiss();
}
})
.show();
}
});
} else {
itemViewHolder.tvSoldOut.setVisibility(View.GONE);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sharedPref = getSharedPreferences("cartitems", 0);
String strJson = sharedPref.getString("cartdata", "0");
try {
mainjsonArray = new JSONArray(strJson);
} catch (JSONException e) {
e.printStackTrace();
}
Intent i = new Intent(RestaurantMenuActivity.this, ProductCartActivity.class);
i.putExtra("product_id", allData.get(section).getProductDetails().get(relativePosition).getProductID());
i.putExtra("productCart", true);
i.putExtra("product_name", allData.get(section).getProductDetails().get(relativePosition).getProductName());
i.putExtra("product_price", allData.get(section).getProductDetails().get(relativePosition).getCurrentPrice());
try {
i.putExtra("jsonArray", mainjsonArray.toString());
} catch (Exception e) {
e.printStackTrace();
}
startActivityForResult(i, PRODUCT_CART);
}
});
}
} else {
rlAddCart.setVisibility(View.GONE);
itemViewHolder.ll_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(RestaurantMenuActivity.this)
.setMessage("Sorry you are not in restaurant")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Your code
dialog.dismiss();
}
})
.show();
}
});
}
if (allData.get(section).getProductDetails().get(relativePosition).getFavorited() == 0) {
itemViewHolder.ivFav.setImageResource(R.drawable.fav_02);
} else {
itemViewHolder.ivFav.setImageResource(R.drawable.favroite_highlited);
}
itemViewHolder.ivFav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ProgressDialog pd = ProgressDialog.show(RestaurantMenuActivity.this, "", "Loading...");
JSONObject postdata = new JSONObject();
try {
YupITApplication.getJsonWithHTTPPost(RestaurantMenuActivity.this, 1, new ServiceCallBack() {
#Override
public void serviceCallback(int id, JSONObject jsonResult) {
pd.dismiss();
try {
if (jsonResult.has("Data") && !jsonResult.getString("Data").equals("")) {
// {"Status":"Success","StatusCode":"200","Message":"Item Favourited!","Data":[]}
if (jsonResult.getString("Message").equalsIgnoreCase("Item Favourited!")) {
itemViewHolder.ivFav.setImageResource(R.drawable.favroite_highlited);
} else {
itemViewHolder.ivFav.setImageResource(R.drawable.fav_02);
}
Toast.makeText(getApplicationContext(), jsonResult.getString("Message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, Utils.insertfavoriteitem + "&productid=" + allData.get(section).getProductDetails().get(relativePosition).getProductID() + "&userid=" + customer_id, postdata);
} catch (Exception e) {
e.printStackTrace();
}
}
});
Glide.with(RestaurantMenuActivity.this).load(allData.get(section).getProductDetails().get(relativePosition).getPhotoImagePath())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(itemViewHolder.ivMenu);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, boolean header) {
View v = null;
if (header) {
v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_section, parent, false);
v.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
width = v.getMeasuredWidth();
height = v.getMeasuredHeight();
return new SectionViewHolder(v);
} else {
v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new ItemViewHolder(v);
}
}
// SectionViewHolder Class for Sections
public class SectionViewHolder extends RecyclerView.ViewHolder {
final TextView tvCategory;
public SectionViewHolder(View itemView) {
super(itemView);
tvCategory = (TextView) itemView.findViewById(R.id.tvCategory);
}
}
// ItemViewHolder Class for Items in each Section
public class ItemViewHolder extends RecyclerView.ViewHolder {
final TextView tvProductName, tvDescription, tvPrice, tvSoldOut;
LinearLayout ll_product;
ImageView ivMenu, ivFav;
public ItemViewHolder(View itemView) {
super(itemView);
tvProductName = (TextView) itemView.findViewById(R.id.tvProductName);
tvDescription = (TextView) itemView.findViewById(R.id.tvDescription);
tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
ivMenu = (ImageView) itemView.findViewById(R.id.ivMenu);
ll_product = (LinearLayout) itemView.findViewById(R.id.ll_product);
tvSoldOut = (TextView) itemView.findViewById(R.id.tvSoldOut);
ivFav = (ImageView) itemView.findViewById(R.id.ivFav);
}
}
public int isSectionHeaderPosition(int position) {
return Integer.parseInt(allData.get(position).getCategoryID());
}
}
Please help
i think that the position of category in popup menu will be the same as section value of the second recyclerView if you get the position of clicked item in your activity by listening on item's click you can scroll the recyclerView using the LayoutManager.
recyclerView.getLayoutManager().scrollToPosition(youPositionInTheAdapter).

notifyItemChanged method does not call onBindViewHolder in recyclerview

My code is as shown below:
public class PopularItemsAdapter extends RecyclerView.Adapter<PopularItemsAdapter.MyViewHolder>
implements MyCartListener {
private Context mContext;
private List<FoodTruckItem> foodTruckItemList;
private boolean isClickable = false;
private OnItemClickListener listener;
private List<FoodtruckInfo> foodtruckInfoList = new ArrayList<>();
private List<FoodTruckItem> sessionItem = new ArrayList<>();
private boolean isConflictResolved = false;
public int position = -1;
#Override
public void itemUpdated(int quantity, String itemId) {
for (int i = 0; i < foodTruckItemList.size(); i++) {
if (itemId.equals(foodTruckItemList.get(i).getItemId())) {
foodTruckItemList.get(i).setItemQuantityOrdered(quantity);
// notifyDataSetChanged();
}
}
}
#Override
public void itemRemoved(String itemId) {
for (int j = 0; j < foodTruckItemList.size(); j++) {
if (itemId.equals(foodTruckItemList.get(j).getItemId())) {
foodTruckItemList.remove(j);
// notifyDataSetChanged();
}
}
}
public void addConflictItem(int position) {
isConflictResolved = true;
notifyItemChanged(position);
}
public interface OnItemClickListener {
void onItemClick(FoodTruckItem foodTruckItem, FoodtruckInfo foodtruckInfo);
void showSnackBar(int items, boolean added, int position);
void showRestaurentClosed();
void showWarningDialog(int position);
}
public void addFoodInfo(List<FoodtruckInfo> foodtruckInfos) {
foodtruckInfoList.addAll(foodtruckInfos);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView itemName, foodPrice, addText, quantityText, addQuantity, removeQuantity;
public ImageView itemImage, itemTag;
public LinearLayout addLayout;
public MyViewHolder(View view) {
super(view);
itemTag = (ImageView) view.findViewById(R.id.itemTag);
itemImage = (ImageView) view.findViewById(R.id.itemImage);
itemName = (TextView) view.findViewById(R.id.itemName);
foodPrice = (TextView) view.findViewById(R.id.foodPrice);
addText = (TextView) view.findViewById(R.id.addText);
addLayout = (LinearLayout) view.findViewById(R.id.addLayout);
quantityText = (TextView) view.findViewById(R.id.quantityText);
addQuantity = (TextView) view.findViewById(R.id.addQuantity);
removeQuantity = (TextView) view.findViewById(R.id.removeQuantity);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
FoodtruckInfo foodtruckInfo = new FoodtruckInfo();
//passing the clicked position to the parent class
for (FoodtruckInfo info : foodtruckInfoList) {
if (info.getItemId().equals(foodTruckItemList.get(getAdapterPosition()).getItemId())) {
foodtruckInfo = info;
}
}
listener.onItemClick(foodTruckItemList.get(getAdapterPosition()), foodtruckInfo);
}
}
public PopularItemsAdapter(Context mContext, List<FoodTruckItem> foodTruckItemList, OnItemClickListener listener) {
this.mContext = mContext;
this.foodTruckItemList = foodTruckItemList;
this.listener = listener;
MyCart.getInstance().addListener(this);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_popular_items, parent, false);
return new MyViewHolder(itemView);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final FoodTruckItem foodTruckItem = foodTruckItemList.get(position);
if (SessionManager.get(mContext).getFoodTruckItemList() != null) {
sessionItem = SessionManager.get(mContext).getFoodTruckItemList();
for (FoodTruckItem item : sessionItem) {
if (item.getItemId().equals(foodTruckItem.getItemId())) {
// holder.itemTag.setText("MY FAVOURITE");
holder.itemTag.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_favorite));
}
}
}
holder.itemName.setText(foodTruckItem.getItemName());
// holder.itemTag.setText(foodTruckItem.getSpecialTag());
holder.foodPrice.setText("$" + String.valueOf(foodTruckItem.getItemPrice()));
Picasso.Builder builder = new Picasso.Builder(mContext);
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
if (!TextUtils.isEmpty(foodTruckItem.getItemImg())) {
builder.build().load(foodTruckItem.getItemImg()).into(holder.itemImage);
}
holder.addText.setOnClickListener(new View.OnClickListener() {
FoodtruckInfo info = new FoodtruckInfo();
#Override
public void onClick(View v) {
for (int l = 0; l < foodtruckInfoList.size(); l++) {
if (foodtruckInfoList.get(l).getItemId().equals(foodTruckItem.getItemId())) {
if (foodtruckInfoList.get(l).getOrderStatus() == 0) {
isClickable = true;
} else {
isClickable = false;
}
}
}
if (isClickable) {
String foodTruckId = null;
if (MyCart.getInstance().getFoodTruckId() != null) {
foodTruckId = MyCart.getInstance().getFoodTruckId();
if (!foodTruckId.equals(foodtruckInfoList.get(position).getFoodTruckId())) {
listener.showWarningDialog(position);
} else {
addItem(holder, position, foodTruckItem);
}
} else {
isConflictResolved = false;
addItem(holder, position, foodTruckItem);
}
} else {
listener.showRestaurentClosed();
}
if (isConflictResolved) {
isConflictResolved = false;
addItem(holder, position, foodTruckItem);
}
}
});
holder.addQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = foodTruckItem.getItemQuantityOrdered();
quantity += 1;
holder.quantityText.setText(String.valueOf(quantity));
MyCart.getInstance().updateQuantity(quantity, foodTruckItem.getItemId(), false);
}
});
holder.removeQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = foodTruckItem.getItemQuantityOrdered();
quantity -= 1;
if (quantity == 0) {
MyCart.getInstance().removeItem(foodTruckItem.getItemId(), false);
holder.addLayout.setVisibility(View.INVISIBLE);
holder.addText.setVisibility(View.VISIBLE);
listener.showSnackBar(quantity, false, position);
} else {
holder.quantityText.setText(String.valueOf(quantity));
MyCart.getInstance().updateQuantity(quantity, foodTruckItem.getItemId(), false);
}
}
});
setFontStyle(holder);
}
private void addItem(MyViewHolder holder, int position, FoodTruckItem foodTruckItem) {
holder.addLayout.setVisibility(View.VISIBLE);
holder.addText.setVisibility(View.INVISIBLE);
foodTruckItem.setItemQuantityOrdered(1);
holder.quantityText.setText(String.valueOf(1));
MyCart.getInstance().addItem(foodTruckItem);
MyCart.getInstance().setFoodTruckId(foodtruckInfoList.get(position).getFoodTruckId());
listener.showSnackBar(MyCart.getInstance().getItemList(), true, position);
}
private void setFontStyle(MyViewHolder holder) {
holder.itemName.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
// holder.itemTag.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
holder.foodPrice.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
holder.addText.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
}
#Override
public int getItemCount() {
return foodTruckItemList.size();
}
}
Here addConflictItem() I have written notifyItemChanged , but somehow it is not calling onBindViewHolder , so is there anything missing in the application?
I was having the same problem, and this worked for me, just add those line to your recyclerview declaration, see this Asnswer
DefaultItemAnimator animator = new DefaultItemAnimator() {
#Override
public boolean canReuseUpdatedViewHolder(RecyclerView.ViewHolder viewHolder) {
return true;
}
};
mRecyclerView.setItemAnimator(animator);
As my experience using setOnClickListener in onBindViewHolder is not good idea.
public class PopularItemsAdapter extends RecyclerView.Adapter<PopularItemsAdapter.MyViewHolder>
implements MyCartListener {
private Context mContext;
private List<FoodTruckItem> foodTruckItemList;
private boolean isClickable = false;
private OnItemClickListener listener;
private List<FoodtruckInfo> foodtruckInfoList = new ArrayList<>();
private List<FoodTruckItem> sessionItem = new ArrayList<>();
private boolean isConflictResolved = false;
public int position = -1;
#Override
public void itemUpdated(int quantity, String itemId) {
for (int i = 0; i < foodTruckItemList.size(); i++) {
if (itemId.equals(foodTruckItemList.get(i).getItemId())) {
foodTruckItemList.get(i).setItemQuantityOrdered(quantity);
// notifyDataSetChanged();
}
}
}
#Override
public void itemRemoved(String itemId) {
for (int j = 0; j < foodTruckItemList.size(); j++) {
if (itemId.equals(foodTruckItemList.get(j).getItemId())) {
foodTruckItemList.remove(j);
// notifyDataSetChanged();
}
}
}
public void addConflictItem(int position) {
isConflictResolved = true;
notifyItemChanged(position);
}
public interface OnItemClickListener {
void onItemClick(FoodTruckItem foodTruckItem, FoodtruckInfo foodtruckInfo);
void showSnackBar(int items, boolean added, int position);
void showRestaurentClosed();
void showWarningDialog(int position);
}
public void addFoodInfo(List<FoodtruckInfo> foodtruckInfos) {
foodtruckInfoList.addAll(foodtruckInfos);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView itemName, foodPrice, addText, quantityText, addQuantity, removeQuantity;
public ImageView itemImage, itemTag;
public LinearLayout addLayout;
MyViewHolder holder;
public MyViewHolder(View view) {
super(view);
itemTag = (ImageView) view.findViewById(R.id.itemTag);
itemImage = (ImageView) view.findViewById(R.id.itemImage);
itemName = (TextView) view.findViewById(R.id.itemName);
foodPrice = (TextView) view.findViewById(R.id.foodPrice);
addText = (TextView) view.findViewById(R.id.addText);
addLayout = (LinearLayout) view.findViewById(R.id.addLayout);
quantityText = (TextView) view.findViewById(R.id.quantityText);
addQuantity = (TextView) view.findViewById(R.id.addQuantity);
removeQuantity = (TextView) view.findViewById(R.id.removeQuantity);
holder = this;
view.setOnClickListener(this);
addText.setOnClickListener(new View.OnClickListener() {
FoodtruckInfo info = new FoodtruckInfo();
#Override
public void onClick(View v) {
int position = getAdapterPosition;
for (int l = 0; l < foodtruckInfoList.size(); l++) {
if (foodtruckInfoList.get(l).getItemId().equals(foodTruckItem.getItemId())) {
if (foodtruckInfoList.get(l).getOrderStatus() == 0) {
isClickable = true;
} else {
isClickable = false;
}
}
}
if (isClickable) {
String foodTruckId = null;
if (MyCart.getInstance().getFoodTruckId() != null) {
foodTruckId = MyCart.getInstance().getFoodTruckId();
if (!foodTruckId.equals(foodtruckInfoList.get(position).getFoodTruckId())) {
listener.showWarningDialog(position);
} else {
addItem(holder, position, foodTruckItem);
}
} else {
isConflictResolved = false;
addItem(holder, position, foodTruckItem);
}
} else {
listener.showRestaurentClosed();
}
if (isConflictResolved) {
isConflictResolved = false;
addItem(holder, position, foodTruckItem);
}
}
});
removeQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition;
int quantity = foodTruckItem.getItemQuantityOrdered();
quantity -= 1;
if (quantity == 0) {
MyCart.getInstance().removeItem(foodTruckItem.getItemId(), false);
holder.addLayout.setVisibility(View.INVISIBLE);
holder.addText.setVisibility(View.VISIBLE);
listener.showSnackBar(quantity, false, position);
} else {
holder.quantityText.setText(String.valueOf(quantity));
MyCart.getInstance().updateQuantity(quantity, foodTruckItem.getItemId(), false);
}
}
});
addQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition;
int quantity = foodTruckItem.getItemQuantityOrdered();
quantity += 1;
holder.quantityText.setText(String.valueOf(quantity));
MyCart.getInstance().updateQuantity(quantity, foodTruckItem.getItemId(), false);
}
});
}
#Override
public void onClick(View view) {
FoodtruckInfo foodtruckInfo = new FoodtruckInfo();
//passing the clicked position to the parent class
for (FoodtruckInfo info : foodtruckInfoList) {
if (info.getItemId().equals(foodTruckItemList.get(getAdapterPosition()).getItemId())) {
foodtruckInfo = info;
}
}
listener.onItemClick(foodTruckItemList.get(getAdapterPosition()), foodtruckInfo);
}
}
public PopularItemsAdapter(Context mContext, List<FoodTruckItem> foodTruckItemList, OnItemClickListener listener) {
this.mContext = mContext;
this.foodTruckItemList = foodTruckItemList;
this.listener = listener;
MyCart.getInstance().addListener(this);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_popular_items, parent, false);
return new MyViewHolder(itemView);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final FoodTruckItem foodTruckItem = foodTruckItemList.get(position);
if (SessionManager.get(mContext).getFoodTruckItemList() != null) {
sessionItem = SessionManager.get(mContext).getFoodTruckItemList();
for (FoodTruckItem item : sessionItem) {
if (item.getItemId().equals(foodTruckItem.getItemId())) {
// holder.itemTag.setText("MY FAVOURITE");
holder.itemTag.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_favorite));
}
}
}
holder.itemName.setText(foodTruckItem.getItemName());
// holder.itemTag.setText(foodTruckItem.getSpecialTag());
holder.foodPrice.setText("$" + String.valueOf(foodTruckItem.getItemPrice()));
Picasso.Builder builder = new Picasso.Builder(mContext);
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
if (!TextUtils.isEmpty(foodTruckItem.getItemImg())) {
builder.build().load(foodTruckItem.getItemImg()).into(holder.itemImage);
}
setFontStyle(holder);
}
private void addItem(MyViewHolder holder, int position, FoodTruckItem foodTruckItem) {
holder.addLayout.setVisibility(View.VISIBLE);
holder.addText.setVisibility(View.INVISIBLE);
foodTruckItem.setItemQuantityOrdered(1);
holder.quantityText.setText(String.valueOf(1));
MyCart.getInstance().addItem(foodTruckItem);
MyCart.getInstance().setFoodTruckId(foodtruckInfoList.get(position).getFoodTruckId());
listener.showSnackBar(MyCart.getInstance().getItemList(), true, position);
}
private void setFontStyle(MyViewHolder holder) {
holder.itemName.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
// holder.itemTag.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
holder.foodPrice.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
holder.addText.setTypeface(Typeface.createFromAsset(mContext.getAssets(), Consts.montserrat_bold));
}
#Override
public int getItemCount() {
return foodTruckItemList.size();
}
}
Just call notifyDataSetChanged() and the RecycleView will refresh

make a List of HashMap type in recycler view adapter

I am using this liabray for swipe gestures. https://github.com/nikhilpanju/RecyclerViewEnhanced.
In the MainAdapter.java class recyclerView contains List but i want to replace this to List> type. When i do this, so many errors appear. Kindly guide me how can i do this or suggest me any tutorial to do that.
MainAdapter.java
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> {
LayoutInflater inflater;
List<RowModel> modelList;
public MainAdapter(Context context, List<RowModel> list) {
inflater = LayoutInflater.from(context);
modelList = new ArrayList<>(list);
}
#Override
public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.recycler_row, parent, false);
return new MainViewHolder(view);
}
#Override
public void onBindViewHolder(MainViewHolder holder, int position) {
holder.bindData(modelList.get(position));
}
#Override
public int getItemCount() {
return modelList.size();
}
class MainViewHolder extends RecyclerView.ViewHolder {
TextView mainText, subText;
public MainViewHolder(View itemView) {
super(itemView);
mainText = (TextView) itemView.findViewById(R.id.mainText);
subText = (TextView) itemView.findViewById(R.id.subText);
}
public void bindData(RowModel rowModel) {
mainText.setText(rowModel.getMainText());
subText.setText(rowModel.getSubText());
}
}
}
Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_panel);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
unclickableRows = new ArrayList<>();
unswipeableRows = new ArrayList<>();
dialogItems = new String[25];
for (int i = 0; i < 25; i++) {
dialogItems[i] = String.valueOf(i + 1);
}
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mAdapter = new MainAdapter(this, getData());
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
onTouchListener = new RecyclerTouchListener(this, mRecyclerView);
onTouchListener
.setIndependentViews(R.id.rowButton)
.setViewsToFade(R.id.rowButton)
.setClickable(new RecyclerTouchListener.OnRowClickListener() {
#Override
public void onRowClicked(int position) {
util.shortToast(getApplicationContext(), "Row " + (position + 1) + " clicked!");
}
#Override
public void onIndependentViewClicked(int independentViewID, int position) {
util.shortToast(getApplicationContext(), "Button in row " + (position + 1) + " clicked!");
}
})
.setSwipeOptionViews(R.id.add, R.id.edit, R.id.change)
.setSwipeable(R.id.rowFG, R.id.rowBG, new RecyclerTouchListener.OnSwipeOptionsClickListener() {
#Override
public void onSwipeOptionClicked(int viewID, int position) {
String message = "";
if (viewID == R.id.add) {
message += "Add";
} else if (viewID == R.id.edit) {
message += "Edit";
} else if (viewID == R.id.change) {
message += "Change";
}
message += " clicked for row " + (position + 1);
util.shortToast(getApplicationContext(), message);
}
});
mRecyclerView.addOnItemTouchListener(onTouchListener);
// Detect touched area
detector = new Swipe(this,this);
db = new DB(getApplicationContext());
Bundle bundle = getIntent().getExtras();
if(bundle != null) {
String id = bundle.getString("id");
Toast.makeText(this, "Welcome " + db.getUsernameById(id), Toast.LENGTH_LONG).show();
}
//get references of layout
// adapter = new AdapterUsers(this, R.layout.textview_users, arrayList);
// listView = (ListView) findViewById(R.id.users);
// listView.setAdapter(adapter);
//
// showAllUsers();
}
public void showAllUsers() {
try {
Cursor cursor = db.selectAllUsers();
cursor.moveToFirst();
adapter.clear();
if (cursor.getCount() == 0) {
Toast.makeText(this, "Empty user list", Toast.LENGTH_SHORT).show();
} else {
for (int i = 0; i < cursor.getCount(); i++) {
HashMap<String, Object> hm = new HashMap<String, Object>();
hm.put(ID, cursor.getString(cursor.getColumnIndex(db.ID_USER)));
hm.put(USERNAME, cursor.getString(cursor.getColumnIndex(db.NAME_USER)));
arrayList.add(hm);
cursor.moveToNext();
}
}
} catch (Exception e) {
Log.d("Show users", " failed due to " + e.getMessage());
}
}
// Swipe interface
#Override
public void onSwipe(int direction) {
String str = "";
switch (direction) {
case Swipe.SWIPE_RIGHT :
listView.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//deleteUser(id);
Toast.makeText(AdminPanel.this, "user deleted", Toast.LENGTH_LONG).show();
}
});
str = "Swipe Right";
break;
case Swipe.SWIPE_LEFT : str = "Swipe Left";
break;
case Swipe.SWIPE_DOWN : str = "Swipe Down";
break;
case Swipe.SWIPE_UP : str = "Swipe Up";
break;
}
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
#Override
public void onDoubleTap() {
Toast.makeText(this, "Double Tap", Toast.LENGTH_SHORT).show();
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (touchListener != null) touchListener.getTouchCoordinates(ev);
return super.dispatchTouchEvent(ev);
}
#Override
public void setOnActivityTouchListener(OnActivityTouchListener listener) {
this.touchListener = listener;
}
private List<RowModel> getData() {
List<RowModel> list = new ArrayList<>(25);
for (int i = 0; i < 25; i++) {
list.add(new RowModel("Row " + (i + 1), "Some Text... "));
}
return list;
}
}
you can change your getData() method and make it return HashMap.
private HashMap <String,String> getData() {
HashMap <String,String> list = new HashMap <String,String>();
for (int i = 0; i < 25; i++) {
list.put(i,"Text");
}
return list;
}
now in your Adapter you can handle it like...
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> {
LayoutInflater inflater;
<HashMap<String,String> modelList;
public MainAdapter(Context context, <HashMap<String,String> modelList) {
this.inflater = LayoutInflater.from(context);
this.modelList = modelList;
}
#Override
public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.recycler_row, parent, false);
return new MainViewHolder(view);
}
#Override
public void onBindViewHolder(MainViewHolder holder, int position) {
//holder.bindData();
holder.mainText.setText(modelList.get(position)); // value for the given key
}
#Override
public int getItemCount() {
return modelList.size();
}
class MainViewHolder extends RecyclerView.ViewHolder {
TextView mainText, subText;
public MainViewHolder(View itemView) {
super(itemView);
mainText = (TextView) itemView.findViewById(R.id.mainText);
subText = (TextView) itemView.findViewById(R.id.subText);
}
}
}

Cannot use finish() inside Adapter

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.

Categories

Resources