I have a problem. If I click on an increase button, the item quantity also increases. When I click on the decrement button, I get the same result. Here is where I declare the ArrayList<>:
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
public static Context c;
int quantity=0;
public static int qty,cty,mty=0,qty1;
public static int sendcost;
public static String curry;
MyHolder holder;
public ArrayList<Integer> quantity1 = new ArrayList<Integer>();
private List<Spacecraft> spacecrafts = new ArrayList<>();
CustomButtonListener customButtonListener;
private boolean mShowQuantity;
public MyAdapter(Context c, ArrayList<Spacecraft> spacecrafts, boolean showQuantity ) {//ArrayList<ShoppingCartEntry> showQuantity , boolean showQuantity
MyAdapter.c = c;
this.spacecrafts = spacecrafts;
this.mShowQuantity = showQuantity;
for(int i =0; i< spacecrafts.size();i++ )
{
quantity1.add(0);
//quantity[i]=0;
}
}
This is where I organise the RecyclerView:
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.model, parent, false);
return new MyHolder(v);
}
#Override
public void onBindViewHolder(final MyHolder holder, final int position) {
final Spacecraft s = spacecrafts.get(position);
holder.nameTxt.setText(s.getName());
PicassoClient.downloadImage(c, s.getImageUrl(), holder.img);
holder.propellentTxt.setText(s.getPropellant());
holder.descTxt.setText(s.getDescription());
holder.carbohydratesTxt.setText(s.getCarbohydrates());
holder.fatcontentTxt.setText(s.getFatcontent());
holder.minaralsTxt.setText(s.getMinarals());
holder.costTxt.setText("" + s.getCost());
holder.rateTxt.getText().toString();
try{
holder.rateTxt.setText(quantity1.get(position)+"");
}catch(Exception e){
e.printStackTrace();
}
MyHolder.btn_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
quantity = Integer.parseInt(holder.rateTxt.getText().toString());
cty = Integer.parseInt(holder.costTxt.getText().toString());
curry =holder.nameTxt.getText().toString();
qty1 = 1;
quantity = quantity + 1;
holder.rateTxt.setText(String.valueOf(quantity));//quantity
sendcost = quantity * cty;//single item cost
mty = mty + cty * qty1;// Total Cost
MainActivity.Totalcost.setText("Total cost :" + String.valueOf(mty));
ShoppingCartHelper.setQuantity(s, quantity);
}
});
Here is my decrease button:
MyHolder.btn_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
qty1=1;
quantity = Integer.parseInt(holder.rateTxt.getText().toString());
cty = Integer.parseInt(holder.costTxt.getText().toString());
if(quantity == 0)
{
}
else
{
quantity = quantity - 1;
holder.rateTxt.setText(String.valueOf(quantity));
mty =mty - cty*qty1;
MainActivity.Totalcost.setText("Total cost :" + String.valueOf(mty));
ShoppingCartHelper.setQuantity(s, quantity);
}
}
});
holder.quan.setVisibility(View.GONE);
return;
}
#Override
public int getItemCount() {
return spacecrafts.size();
}
}
Any suggestions on how to make the decrease button work?
Based on the information in the comments, they are all accurate. You need to update the ArrayList<> each time you increase and decrease the quantities. After you do that, you need to notify your RecyclerViews adapter like so:
quantity1.set(position, quantity);
notifyDataSetChanged();
When you update the ArrayList<>, any new changes that were made would appear in the RecyclerView.
Related
hi I want to make a recycler view in two different fragments in which one fragment has limit recycler view list which is shown only 4 lists and another fragment in which all the list item is shown, thanks in advance.
main class code,
private void populatelist() {
List<reviewModel> reviewModelList = new ArrayList<>();
for (int i = 1; i < 20; i++) {
int imges = R.drawable.ic_userlogin;
String names = "User Name is " + i;
String dates = "New Dates is " + i;
String detail = "User details about is " + i;
reviewModel models = new reviewModel(names, dates, detail, 4, imges);
reviewModelList.add(models);
}
setupRecycle(reviewModelList);
}
private void setupRecycle(List<reviewModel> reviewModelList) {
if (adaptOverView == null)
adaptOverView = new reviewAdapt(this, 5);
adaptOverView.setReviewList(reviewModelList);
LinearLayoutManager layout = new LinearLayoutManager(this);
layout.setSmoothScrollbarEnabled(true);
recyclerOverView.setLayoutManager(layout);
recyclerOverView.setHasFixedSize(true);
recyclerOverView.setAdapter(adaptOverView);
}
adapter class code,
private Context mContext;
private List<reviewModel> reviewList;
private int limit;
public void setReviewList(List<reviewModel> list){
this.reviewList = list;
this.notifyDataSetChanged();
}
public reviewAdapt(Context mContext, int limit) {
this.mContext = mContext;
this.limit = limit;
}
public reviewAdapt(Context mContext, List<reviewModel> reviewList, int limit) {
this.mContext = mContext;
this.reviewList = reviewList;
this.limit = limit;
}
#NonNull
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.review_design, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
if (position < limit) {
reviewModel model = reviewList.get(position);
Log.d("TAG", "onBindViewHolder_Limit: "+limit);
Log.d("TAG", "onBindViewHolder_Position_Is_InLimit: "+position);
holder.textViewName.setText(model.getName());
holder.textViewDate.setText(model.getDate());
holder.ratingBarRecycle.setRating(model.getRatingBar());
holder.textViewDetails.setText(model.getDetails());
holder.imageViewRecycle.setImageResource(model.getImg());
}
}
#Override
public int getItemCount() {
return reviewList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView textViewName, textViewDate, textViewDetails;
RatingBar ratingBarRecycle;
ImageView imageViewRecycle;
public ViewHolder(#NonNull View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.name_review);
textViewDate = itemView.findViewById(R.id.date_review);
textViewDetails = itemView.findViewById(R.id.details_review);
ratingBarRecycle = itemView.findViewById(R.id.review_ratingsBar);
imageViewRecycle = itemView.findViewById(R.id.profile_image);
}
}
}
As per my understanding , You are using limit variable for restricting listing size for fragment. But you are not using it rightly. If I am not wrong, Try to restrict item count for in adapter as below -
#Override
public int getItemCount() {
return limit;
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ContactViewHolder> {
static final String myTag = "DocsUpload";
ArrayList<RecyclerItem> listItems = new ArrayList<>();
RecyclerView.ViewHolder holder;
int clickcount=0;
private Context mContext;
List list = new ArrayList();
Boolean signUpModeActive = true;
public MyAdapter(ArrayList<RecyclerItem> listItems, Context mContext) {
this.listItems = listItems;
this.mContext = mContext;
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
ContactViewHolder contactViewHolder = new ContactViewHolder(view, mContext, listItems);
return contactViewHolder;
}
#Override
public void onBindViewHolder(final ContactViewHolder holder, final int position) {
RecyclerItem itemList = listItems.get(position);
holder.txtTitle.setText(itemList.getTitle());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ContactViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtTitle;
public CheckBox checkBox;
public TextView txtDescription;
public ImageView txtOptionDigit;
ArrayList<RecyclerItem> listitems = new ArrayList<RecyclerItem>();
Context ctx;
public ContactViewHolder(View view, Context ctx, ArrayList<RecyclerItem> listitems) {
super(view);
this.listitems = listitems;
this.ctx = ctx;
view.setOnClickListener(this);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
checkBox = (CheckBox) itemView.findViewById(R.id.checkBoxxml);
}
boolean m=false;
#Override
public void onClick(View v) {
clickcount=clickcount+1;
Log.e("count", String.valueOf(clickcount));
int position = getAdapterPosition();
final RecyclerItem listitems = this.listitems.get(position);
final String getname = listitems.getTitle();
if (signUpModeActive=true) {
signUpModeActive = false;
listItems.get(position).setTitle("");
listItems.get(position).setTitle(getname + " " +"absent");
} else {
signUpModeActive = true;
listItems.get(position).setTitle("");
listItems.get(position).setTitle(getname + " " +"present");
}
notifyDataSetChanged();
}
}
public void getsetadapt(String pos) {
list.add(pos);
Log.e("listdata", String.valueOf(list));
for (int i=0;i < list.size();i++)
{
Log.i("Value "+i, String.valueOf(list.get(i)));
i++;
}
}
when I click any list items it want add absent to existing text and if I click it again it want to replace absent with present..can any one know where iam going wrong ...and if run this code at my emulator it works and it is adding the text it is not replacing. For example the if I click student oviya its adding text absent near to oviya but if I click it again it is not replacing its is adding present next to that again and again
Just change your adapter to the following adapter and it will work fine
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ContactViewHolder> {
static final String myTag = "DocsUpload";
ArrayList<RecyclerItem> listItems = new ArrayList<>();
RecyclerView.ViewHolder holder;
int clickcount = 0;
private Context mContext;
List list = new ArrayList();
Boolean signUpModeActive = true;
public MyAdapter(ArrayList<RecyclerItem> listItems, Context mContext) {
this.listItems = listItems;
this.mContext = mContext;
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item_2, parent, false);
ContactViewHolder contactViewHolder = new ContactViewHolder(view, mContext, listItems);
return contactViewHolder;
}
#Override
public void onBindViewHolder(final ContactViewHolder holder, final int position) {
RecyclerItem itemList = listItems.get(position);
holder.txtTitle.setText(itemList.getTitle());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ContactViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtTitle;
public CheckBox checkBox;
public TextView txtDescription;
public ImageView txtOptionDigit;
ArrayList<RecyclerItem> listitems = new ArrayList<RecyclerItem>();
Context ctx;
public ContactViewHolder(View view, Context ctx, ArrayList<RecyclerItem> listitems) {
super(view);
this.listitems = listitems;
this.ctx = ctx;
view.setOnClickListener(this);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
checkBox = (CheckBox) itemView.findViewById(R.id.checkBoxxml);
}
boolean m = false;
#Override
public void onClick(View v) {
clickcount = clickcount + 1;
Log.e("count", String.valueOf(clickcount));
int position = getAdapterPosition();
final RecyclerItem listitems = this.listitems.get(position);
final String getname = listitems.getTitle().replace(" absent" , "").replace(" present" , "");
if (signUpModeActive ) {
signUpModeActive = false;
listItems.get(position).setTitle(getname + " " + "absent");
} else {
signUpModeActive = true;
listItems.get(position).setTitle(getname + " " + "present");
}
notifyDataSetChanged();
}
}
public void getsetadapt(String pos) {
list.add(pos);
Log.e("listdata", String.valueOf(list));
for (int i = 0; i < list.size(); i++) {
Log.i("Value " + i, String.valueOf(list.get(i)));
i++;
}
}
}
Actually the problem was in line
final RecyclerItem listitems = this.listitems.get(position);
final String getname = listitems.getTitle();
you were setting text as
listItems.get(position).setTitle(getname + " " + "absent");
OR
listItems.get(position).setTitle(getname + " " + "present");
This will result as Name absent or Name present as result and will add a new absent or present to it
There are different problems in your code.
1
First of all, your variables are not named correctly so it's very confusing. For example you use listitems and listItems which are almost exactly the same. Plus listitems is used twice for 2 different variables with the exact same case in the same scope!
A variable should describe its content (you should understand what it is when you read the name, for example a list of students will not be named 'list' but 'students' or 'studentsList') AND you should avoid to have 2 variables with the exact same name in the same scope (if you have to start doing something like this.myvariable = myvariable it means something is wrong in your implementation).
2 Manage your title differently
What you want is the name + a status depending on if present or not.
So when you do that:
listItems.get(position).setTitle("");
you just loose the name as listItems and listitems are the exact same list.
So I'd suggest to have a getName() method on RecyclerItem to return the name. Remove the set/getTitle ones.
Then you manage the present/absent with a boolean.
Basically, like that:
if (signUpModeActive = true) {
signUpModeActive = false;
item.setIsPresent(false);
} else {
signUpModeActive = true;
item.setIsPresent(true);
}
It means you need to add a setIsPresent method to the RecyclerItem.
Then you, in the onBindViewHolder you do:
#Override
public void onBindViewHolder(final ContactViewHolder holder, final int position) {
RecyclerItem item = mListItems.get(position);
String name = item.getName();
String status = item.isPresent() ? "present" : "absent";
String title = name + " " + status;
holder.txtTitle.setText(title);
}
It'd be even better to use a string resource with a placeholder to manage the text of the status.
I'm using RecyclerView to display a list of marks, and each mark of the value is shown as a CardView.
But some contents of the cards are lost after the scrolling the RecyclerView down and scrolling back, as shown in the two screenshots below.
The contents of the red rectangle are lost after scrolling.
public class Shop_Products_adapter extends
RecyclerView.Adapter<Shop_Products_adapter.MyViewHolder> {
public static HashMap<String, String> cartHasmap = new HashMap<String, String>();
private List<Shop_Products> ServiceModels = new ArrayList<>();
private Context mContext;
private int count = 0;
public Shop_Products_adapter(List<Shop_Products> ServiceModels, Context mContext) {
this.ServiceModels = ServiceModels;
Log.e("Shop_Products_adapter", ServiceModels.toString());
this.mContext = mContext;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.shop_products, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
final Shop_Products serviceModel = ServiceModels.get(position);
Log.e("onBindViewHolder", serviceModel.getName1());
holder.name1.setText(serviceModel.getName1());
holder.cost1.setText("\u20B9 " + serviceModel.getCost());
holder.kgs1.setText(serviceModel.getKgs() + " kgs");
String urlOfImage = serviceModel.getImage1();
Picasso.with(mContext).load(urlOfImage).into(holder.image1);
final List quantity = new ArrayList<Integer>();
for (int i = 0; i <= 10; i++) {
quantity.add(Integer.toString(i));
}
ArrayAdapter<Integer> spinnerArrayAdapter = new ArrayAdapter<Integer>(mContext, android.R.layout.simple_spinner_item, quantity);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.quatity_spinner.setAdapter(spinnerArrayAdapter);
//holder.quatity_spinner.setSelection(position,true);
holder.quatity_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (holder.quatity_spinner.getSelectedItem().equals("0")) {
cartHasmap.put(serviceModel.getId(), serviceModel.getQty());
cartHasmap.values().removeAll(Collections.singleton(serviceModel.getQty()));
Log.e("cartHasmap Remove Valeu", "onItemSelected() returned: " + cartHasmap);
} else {
count = count + 1;
serviceModel.setCount(String.valueOf(count));
String qty = holder.quatity_spinner.getSelectedItem().toString();
serviceModel.setQty(qty);
SharedPreferences pref = mContext.getSharedPreferences("cart_data", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("count", count);
editor.putString("qty", qty);
editor.putString("product_id", serviceModel.getId());
editor.commit();
cartHasmap.put(serviceModel.getId(), serviceModel.getQty());
Log.e("cartHasmap", "onItemSelected() returned: " + cartHasmap);
Log.e("*******", "onitem get id " + serviceModel.getId());
JSONObject object = new JSONObject();
try {
object.put("", serviceModel.getQty());
object.put("", serviceModel.getId());
Log.i("+++++++++", "onItemSelected: " + object);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public int getItemCount() {
return ServiceModels.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public void setFilter(ArrayList<Shop_Products> filter) {
ServiceModels = new ArrayList<>();
ServiceModels.addAll(filter);
notifyDataSetChanged();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name1;
public TextView cost1;
public TextView kgs1;
public ImageView image1;
public Spinner quatity_spinner;
public MyViewHolder(View view) {
super(view);
name1 = (TextView) view.findViewById(R.id.name1);
cost1 = (TextView) view.findViewById(R.id.cost);
kgs1 = (TextView) view.findViewById(R.id.kgs);
image1 = (ImageView) view.findViewById(R.id.img1);
quatity_spinner = (Spinner) view.findViewById(R.id.quatity_spinner);
}
}
}
I face a problem in list view. In my list view have edit text and text view. When i scroll the list my data that is entered in text view has lost the value and show the default value. i have two button in list view i increase the quantity and scroll the list for next product when i come back text view lost the value and show default value 1 . And when i open keyboard for enter data then same issue . please help me.
And its my code
Custom Adapter
private List<ShowProducts> listShowProducts;
private Context context;
private int resource;
private String condition;
String uri;
private static final String TAG = "CustomAdapter";
int i = 0;
float total;
ListView listView;
TextView tvTotal;
float sum = 0;
public CustomAdapter(#NonNull Context context, #LayoutRes int resource, List<ShowProducts> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.listShowProducts = objects;
}
#Override
public int getCount() {
return super.getCount();
}
#Nullable
#Override
public Object getItem(int position) {
return super.getItem(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(resource, parent, false);
{
final ShowProducts showProducts = listShowProducts.get(position);
ImageView imageView = (ImageView) view.findViewById(R.id.imageViewOfSelecteditem);
ImageView plus = (ImageView) view.findViewById(R.id.imageviewPlus);
ImageView minus = (ImageView) view.findViewById(R.id.imageviewminus);
TextView tvSetNameOfSeletedItem = (TextView) view.findViewById(R.id.tvSetNameOfSeletedItem);
TextView tvSetSizeOfSeletedItem = (TextView) view.findViewById(R.id.tvSetSizeOfSeletedItem);
TextView tvSetPriceOfSeletedItem = (TextView) view.findViewById(R.id.tvSetPriceOfSeletedItem);
final TextView tvQunatitySetOfSelectedItem = (TextView) view.findViewById(R.id.tvQunatitySetOfSelectedItem);
for (int a = 0; a < 10; a++) {
Log.d(TAG, "onnnnView: ");
}
Log.d(TAG, "getView: +++++");
tvSetNameOfSeletedItem.setText(showProducts.getProduct_name().toString());
tvSetSizeOfSeletedItem.setText(showProducts.getSize_name());
tvSetPriceOfSeletedItem.setText(String.valueOf(showProducts.getSize_price()).toString());
uri = showProducts.getProduct_photo().toString();
Picasso.with(context).load(uri).into(imageView);
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(tvQunatitySetOfSelectedItem.getText().toString());
a++;
Log.d(TAG, "getView: ");
if (a <= showProducts.getSize_quantity()) {
tvQunatitySetOfSelectedItem.setText(String.valueOf(a).toString());
tvTotal = (TextView) ((Activity) context).findViewById(R.id.tvTotalShow);
float price = Float.parseFloat(tvTotal.getText().toString());
sum = price + showProducts.getSize_price();
tvTotal.setText(String.valueOf(sum));
}
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(tvQunatitySetOfSelectedItem.getText().toString());
a--;
if (a > 0)
{
tvQunatitySetOfSelectedItem.setText(String.valueOf(a).toString());
tvTotal = (TextView) ((Activity) context).findViewById(R.id.tvTotalShow);
float price = Float.parseFloat(tvTotal.getText().toString());
sum = price - showProducts.getSize_price();
tvTotal.setText(String.valueOf(sum));
}
}
});
}
return view;
}
And activity code
public class SelectedProductFromShopingCartShow extends AppCompatActivity {
ArrayList<ShowProducts> arrayList = new ArrayList<>();
String condition = "SelectedItemsFromShoppingCart";
CustomAdapter customAdapter;
ListView listView;
TextView tvTotal;
EditText etDiscount;
int total;
float sum = 0;
Button discount;
private static final String TAG = "SelectedProductFromShop";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selected_product_from_shoping_cart_show);
listView = (ListView) findViewById(R.id.listViewSelectedItemsOfShopingCart);
tvTotal = (TextView) findViewById(R.id.tvTotalShow);
etDiscount = (EditText) findViewById(R.id.etDiscount);
arrayList = (ArrayList<ShowProducts>) getIntent().getSerializableExtra("selectedList");
ShowProducts showProducts = arrayList.get(0);
Log.d(TAG, "onnnnCreate: " + showProducts.getProduct_name());
customAdapter = new CustomAdapter(SelectedProductFromShopingCartShow.this, R.layout.show_selected_item_of_shopingcart, condition, arrayList);
listView.setAdapter(customAdapter);
getTotalListView();
Log.d(TAG, "onnnnCreate: Before inner class");
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(SelectedProductFromShopingCartShow.this);
builder.setTitle("Delete this product");
builder.setMessage("Are you sure you want to delete it?");
builder.setCancelable(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
arrayList.remove(position);
customAdapter.notifyDataSetChanged();
Toast.makeText(SelectedProductFromShopingCartShow.this, "item deleted", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.show();
return true;
}
});
}
public void getTotalListView() {
sum = 0;
for (int i = 0; i < arrayList.size(); i++) {
ShowProducts showProducts = arrayList.get(i);
sum = sum + showProducts.getSize_price();
tvTotal.setText(String.valueOf(sum));
}
}
And watch this video for understand problems
https://youtu.be/WAjtRkI5dl4
You need to follow viewholder pattern. It will resolve your issue. You can check it here https://developer.android.com/training/improving-layouts/smooth-scrolling.html
The only place you're keeping count is in the view. You should make your count a field in the list item ShowProducts and create a getter & setter. For example, in the plus onClickListener, instead of
int a = Integer.parseInt(tvQunatitySetOfSelectedItem.getText().toString());
a++;
You'll have
// for example, in the `plus` listener
int a = showProducts.getCount();
a++;
showProducts.setCount(a);
And don't forget
notifyDataSetChanged();
I have a TextView outside ListView and i need to add prices when the plus button (ie,quantity is incremented )in ListView is clicked.In my program i am not able to add prices when new position ListView button is clicked.I need to find the total price to be payed by the customer when plus button is clicked in ListView
public class ListAdapter1 extends BaseAdapter {
public int qty=1;
public ArrayList<Integer> quantity = new ArrayList<Integer>();
private TextView total;
private String[] listViewItems,prices,weight;
TypedArray images;
public static int pValue;
private Context context;
public static boolean t=false;
CustomButtonListener customButtonListener;
public void setTextView(TextView total)
{
this.total = total;
}
public ListAdapter1(Context context, String[] listViewItems, TypedArray images, String[] weight, String[] prices) {
this.context = context;
this.listViewItems = listViewItems;
this.images = images;
this.prices=prices;
this.weight=weight;
}
public void setCustomButtonListener(CustomButtonListener customButtonListner)
{
this.customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return 5;
}
#Override
public String getItem(int position) {
return listViewItems[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View row;
final ListViewHolder listViewHolder;
if(convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.product,parent,false);
listViewHolder = new ListViewHolder();
listViewHolder.tvProductName = (TextView) row.findViewById(R.id.tvProductName)
listViewHolder.tvPrices = (TextView) row.findViewById(R.id.tvProductPrice);
listViewHolder.btnPlus = (ImageButton) row.findViewById(R.id.ib_addnew);
listViewHolder.edTextQuantity = (EditText) row.findViewById(R.id.editTextQuantity);
listViewHolder.btnMinus = (ImageButton) row.findViewById(R.id.ib_remove);
row.setTag(listViewHolder);
}
else
{
row=convertView;
listViewHolder= (ListViewHolder) row.getTag();
}
try{
listViewHolder.edTextQuantity.setText(quantity.get(position) );
}catch(Exception e){
e.printStackTrace();
}
listViewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, " " + position, Toast.LENGTH_SHORT).show();
int mValue = Integer.parseInt(listViewHolder.edTextQuantity.getText().toString());
if (mValue <=0) {
System.out.println("not valid");
mValue=0;
listViewHolder.edTextQuantity.setText("" +mValue);
}
else{
pValue=pValue/mValue;
mValue--;
pValue=pValue*mValue;
total.setText(String.valueOf(pValue));
System.out.println("mvalue after reducing-----------"+mValue);
System.out.println("pvalue-----------"+pValue);
listViewHolder.edTextQuantity.setText( "" +mValue );
}
}
});
listViewHolder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, " " + position, Toast.LENGTH_SHORT).show();
int mValue = Integer.parseInt(listViewHolder.edTextQuantity.getText().toString());
pValue=Integer.parseInt(listViewHolder.tvPrices.getText().toString());
mValue++;
listViewHolder.edTextQuantity.setText("" + mValue);
System.out.println("mValue after increment---" + mValue);
pValue=pValue*mValue;
System.out.println("pvalue-----------"+pValue);
total.setText(String.valueOf(pValue));
}
});
return row;
}
I need to get total price when any of the ListView button is clicked.
First you need to store value in HashMap<> when user click the plus and minus button.
Then sum the all values in HashMap.
For Example
try{
int sum = 0;
for(HashMap<String, String> map : arrayList) {
sum += Integer.parseInt(map.get("mark"));
}
} catch (Exception e) {
//Manage your exception
}
// sum has the value for the marks total.
System.out.println("Total Marks: "+sum);
Refere my previous answer Here
For that you need to create interface which notify in activity where you want that count.
put snippet in adapter to initialize interface and setter.
public interface IEvent {
void onItemChange(int count);
}
private IEvent iEvent;
//setter method for interface
public void setQuanityEvent(IEvent ievent) {
this.lastPageHandler = handler;
}
put this code in btnMinus.setOnClickListener
//if ievent interface variable register via set
if (ievent != null) {
//pValue is quality COUNT you want to send outside listview.
ievent.onItemChange(pValue);
}
activity code after creating adapter instance
//ListAdapter1 adapter = new ListAdapter1(your params);
adapter.setQuanityEvent(new ListAdapter1.IEvent() {
#Override
public void onItemChange(int count) {
}
}
});