Cart item Count increment/decrement & Sum of cart price - android

I need to increment / decrement of cart product.Valuse are increased / decreased.But from here I need to get Total sum of my all cart product. Got some calculation mistakes.So please help me to fix it.
cartList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> parent, View itemView, final int position, final long rowId) {
txt_cartProduct = (TextView) itemView.findViewById(R.id.cartProduct);
txt_cartQuantity = (TextView) itemView.findViewById(R.id.cartQuantity);
txt_cartPrice = (TextView) itemView.findViewById(R.id.cartPrice);
txt_cartPriceDum = (TextView) itemView.findViewById(R.id.cartPriceDum);
txt_cartCount = (TextView) itemView.findViewById(R.id.cartCount);
img_ivDecrease = (ImageView) itemView.findViewById(R.id.ivDecrease);
img_ivIncrease = (ImageView) itemView.findViewById(R.id.ivIncrease);
but_addTowish = (Button) itemView.findViewById(R.id.addTowish);
but_remove = (Button) itemView.findViewById(R.id.remove);
img_ivIncrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strPrice = txt_cartPrice.getText().toString();
price = Integer.parseInt(strPrice);
int counter = 0;
try {
counter = Integer.parseInt(txt_cartCount.getText().toString());
} catch (NumberFormatException e) {
e.printStackTrace();
}
counter++;
if (counter > 0) {
txt_cartCount.setText(Integer.toString(counter));
txt_cartPrice.setVisibility(View.GONE);
txt_cartPriceDum.setVisibility(View.VISIBLE);
quantity = txt_cartCount.getText().toString();
total = (Integer.parseInt(quantity)) * (price);
netA = String.valueOf(total);
sum += price;
if (sum == 0) {
netAmount = Integer.parseInt(txt_cartPriceDum.getText().toString());
}
netAmount = sum;
Log.e("Sum is", String.valueOf(sum));
txt_cartPriceDum.setText(String.valueOf(total));
cartCount = Integer.parseInt(quantity);
Toast.makeText(context, "netAmount" + netAmount + "\n" + "Total" + total, Toast.LENGTH_SHORT).show();
if (counter == 1) {
cartPrice = price;
cartSum = sum;
}
if (counter == 0) {
cartPrice = 0;
cartSum = 0;
cartCount = 0;
Toast.makeText(context, "Minimum Item is 1", Toast.LENGTH_SHORT).show();
}
int count_check = 1;
if (count_check >= position) {
count_check++;
} else if (count_check == 0) {
Toast.makeText(context, "Minimum Item is 1", Toast.LENGTH_SHORT).show();
}
}
}
});
img_ivDecrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strPrice = txt_cartPrice.getText().toString();
price = Integer.parseInt(strPrice);
int counter = 0;
try {
counter = Integer.parseInt(txt_cartCount.getText().toString());
} catch (NumberFormatException e) {
e.printStackTrace();
}
counter--;
if (counter > 0) {
txt_cartCount.setText(Integer.toString(counter));
txt_cartPrice.setVisibility(View.GONE);
txt_cartPriceDum.setVisibility(View.VISIBLE);
quantity = txt_cartCount.getText().toString();
total = (Integer.parseInt(quantity)) * (price);
netA = String.valueOf(total);
sum -= price;
if (sum == 0) {
netAmount = Integer.parseInt(txt_cartPriceDum.getText().toString());
}
Log.e("Sum - is", String.valueOf(sum));
txt_cartPriceDum.setText(String.valueOf(total));
cartCount = Integer.parseInt(quantity);
Toast.makeText(context, "netAmount" + netAmount + "\n" + "Total" + total, Toast.LENGTH_SHORT).show();
if (counter == 1) {
cartPrice = price;
cartSum = sum;
}
if (counter == 0) {
cartPrice = 0;
cartSum = 0;
cartCount = 0;
}
}
}
});
}
});

Related

Items not displaying orderwise in Recycler View

In my Recycler View not displaying the item orderwise routinely changing the items for each and every time while running the program.
How to display Order wise the items in Recycler View.
Code:
final CustomLinearLayoutManagercartpage layoutManager = new CustomLinearLayoutManagercartpage(CartItems.this, LinearLayoutManager.VERTICAL, false);
recyleitems.setHasFixedSize(false);
recyleitems.setLayoutManager(layoutManager);
cartadapter = new CartlistAdapter(cart, CartItems.this);
Log.i(String.valueOf(cartadapter), "cartadapter");
recyleitems.setAdapter(cartadapter);
recyleitems.setNestedScrollingEnabled(false);
myView.setVisibility(View.GONE);
cartadapter.notifyDataSetChanged();
Adapter:
public class CartlistAdapter extends RecyclerView.Adapter < CartlistAdapter.ViewHolder > {
private ArrayList < CartItemoriginal > cartlistadp;
private ArrayList < Cartitemoringinaltwo > cartlistadp2;
DisplayImageOptions options;
private Context context;
public static final String MyPREFERENCES = "MyPrefs";
public static final String MYCARTPREFERENCE = "CartPrefs";
public static final String MyCartQtyPreference = "Cartatyid";
SharedPreferences.Editor editor;
SharedPreferences shared,
wishshared;
SharedPreferences.Editor editors;
String pos,
qtyDelete;
String date;
String currentDateandTime;
private static final int VIEW_TYPE_ONE = 1;
private static final int VIEW_TYPE_TWO = 2;
private static final int TYPE_HEADER = 0;
private Double orderTotal = 0.00;
DecimalFormat df = new DecimalFormat("0");
Double extPrice;
View layout,
layouts;
SharedPreferences sharedPreferences;
SharedPreferences.Editor QutId;
boolean flag = false;
public CartlistAdapter() {
}
public CartlistAdapter(ArrayList < CartItemoriginal > cartlistadp, Context context) {
this.cartlistadp = cartlistadp;
this.cartlistadp2 = cartlistadp2;
this.context = context;
options = new DisplayImageOptions.Builder().cacheOnDisk(true).cacheInMemory(true).showImageOnLoading(R.drawable.b2)
.showImageForEmptyUri(R.drawable.b2).build();
if (YelloPage.imageLoader.isInited()) {
YelloPage.imageLoader.destroy();
}
YelloPage.imageLoader.init(ImageLoaderConfiguration.createDefault(context));
}
public int getItemViewType(int position) {
if (cartlistadp.size() == 0) {
Toast.makeText(context, String.valueOf(cartlistadp), Toast.LENGTH_LONG).show();
return VIEW_TYPE_TWO;
}
return VIEW_TYPE_ONE;
}
#Override
public CartlistAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
ViewHolder viewHolder = null;
switch (position) {
case VIEW_TYPE_TWO:
View view2 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_cart, viewGroup, false);
viewHolder = new ViewHolder(view2, new MyTextWatcher(viewGroup, position));
// return view holder for your placeholder
break;
case VIEW_TYPE_ONE:
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cartitemrow, viewGroup, false);
viewHolder = new ViewHolder(view, new MyTextWatcher(view, position));
// return view holder for your normal list item
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(CartlistAdapter.ViewHolder viewHolder, int position) {
viewHolder.productnames.setText(cartlistadp.get(position).getProductname());
viewHolder.cartalisname.setText(cartlistadp.get(position).getAliasname());
viewHolder.cartprice.setText("Rs" + " " + cartlistadp.get(position).getPrice());
viewHolder.cartdelivery.setText(cartlistadp.get(position).getDelivery());
viewHolder.cartshippin.setText(cartlistadp.get(position).getShippincharge());
viewHolder.cartsellername.setText(cartlistadp.get(position).getSellername());
viewHolder.Error.setText(cartlistadp.get(position).getError());
viewHolder.qty.setTag(cartlistadp.get(position));
viewHolder.myTextWatcher.updatePosition(position);
if (cartlistadp.get(position).getQty() != 0) {
viewHolder.qty.setText(String.valueOf(cartlistadp.get(position).getQty()));
viewHolder.itemView.setTag(viewHolder);
} else {
viewHolder.qty.setText("0");
}
YelloPage.imageLoader.displayImage(cartlistadp.get(position).getProductimg(), viewHolder.cartitemimg, options);
}
#Override
public int getItemCount() {
return cartlistadp.size();
}
public long getItemId(int position) {
return position;
}
public Object getItem(int position) {
return cartlistadp.get(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView productnames, cartalisname, cartprice, cartdelivery, cartshippin, cartsellername, Error, total;
private ImageView cartitemimg;
private ImageButton wishbtn, removebtn;
private LinearLayout removecart, movewishlist;
private CardView cd;
private EditText qty;
private ImageView WishImg;
public MyTextWatcher myTextWatcher;
public ViewHolder(final View view, MyTextWatcher myTextWatcher) {
super(view);
productnames = (TextView) view.findViewById(R.id.cartitemname);
cartalisname = (TextView) view.findViewById(R.id.cartalias);
cartprice = (TextView) view.findViewById(R.id.CartAmt);
cartdelivery = (TextView) view.findViewById(R.id.cartdel);
cartshippin = (TextView) view.findViewById(R.id.shippingcrg);
cartsellername = (TextView) view.findViewById(R.id.cartSellerName);
cartitemimg = (ImageView) view.findViewById(R.id.cartimg);
Error = (TextView) view.findViewById(R.id.error);
this.myTextWatcher = myTextWatcher;
removecart = (LinearLayout) view.findViewById(R.id.removecart);
movewishlist = (LinearLayout) view.findViewById(R.id.movewishlist);
WishImg = (ImageView) view.findViewById(R.id.wishimg);
qty = (EditText) view.findViewById(R.id.quantity);
qty.addTextChangedListener(myTextWatcher);
String pid, qid;
sharedPreferences = view.getContext().getSharedPreferences(MYCARTPREFERENCE, Context.MODE_PRIVATE);
QutId = sharedPreferences.edit();
Log.d("Position checking1 ---", String.valueOf(getAdapterPosition()));
//MyTextWatcher textWatcher = new MyTextWatcher(view,qty);
// qty.addTextChangedListener(new MyTextWatcher(view,getAdapterPosition()));
//qty.addTextChangedListener(textWatcher);
qty.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
qty.setSelection(qty.getText().length());
return false;
}
});
wishshared = view.getContext().getSharedPreferences(MyPREFERENCES, context.MODE_PRIVATE);
editors = view.getContext().getSharedPreferences(MyPREFERENCES, context.MODE_PRIVATE).edit();
shared = view.getContext().getSharedPreferences(MYCARTPREFERENCE, context.MODE_PRIVATE);
editor = view.getContext().getSharedPreferences(MYCARTPREFERENCE, context.MODE_PRIVATE).edit();
cd = (CardView) view.findViewById(R.id.cv);
productnames.setSingleLine(false);
productnames.setEllipsize(TextUtils.TruncateAt.END);
productnames.setMaxLines(2);
//totalPrice();
view.setClickable(true);
// view.setFocusableInTouchMode(true);
removecart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (cartlistadp.size() == 1) {
Intent list = new Intent(v.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
removeAt(getAdapterPosition());
Log.i(String.valueOf(getPosition()), "item");
Toast.makeText(context, "All items deleted from your WishList", Toast.LENGTH_LONG).show();
} else {
removeAt(getAdapterPosition());
}
}
});
MovewishList();
totalPrice();
}
private void totalPrice() {
int price = 0;
for (int j = 0; j < cartlistadp.size(); j++) {
price += Integer.parseInt(cartlistadp.get(j).getPrice()) * (cartlistadp.get(j).getQty());
String totalprice = String.valueOf(price);
String count = String.valueOf(cartlistadp.size());
CartItems.Totalamt.setText(totalprice);
CartItems.cartcount.setText("(" + count + ")");
CartItems.carttotalcount.setText("(" + count + ")");
}
}
public void removeAt(int positions) {
JSONArray test = new JSONArray();
JSONArray test1 = new JSONArray();
JSONArray test2 = new JSONArray();
JSONArray item = null;
JSONArray itemsQty = null;
test1.put("0");
test2.put("0");
test.put(test1);
test.put(test2);
String channel = shared.getString(Constants.cartid, String.valueOf(test));
pos = cartlistadp.get(getAdapterPosition()).getProductid();
qtyDelete = String.valueOf(cartlistadp.get(getAdapterPosition()).getQty());
try {
JSONArray delteitems = new JSONArray(channel);
itemsQty = delteitems.getJSONArray(0);
item = delteitems.getJSONArray(1);
for (int x = 0; x < itemsQty.length(); x++) {
if (pos.equalsIgnoreCase(itemsQty.getString(x))) {
itemsQty.remove(x);
cartlistadp.remove(positions);
notifyItemRemoved(positions);
notifyItemRangeChanged(positions, cartlistadp.size());
notifyDataSetChanged();
}
}
for (int y = 0; y < item.length(); y++) {
if (qtyDelete.equalsIgnoreCase(item.getString(y)))
item.remove(y);
}
String s = String.valueOf(delteitems);
editor.putString(Constants.cartid, String.valueOf(delteitems));
editor.apply();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void MovewishList() {
movewishlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cartlistadp.size() == 1) {
pos = cartlistadp.get(getAdapterPosition()).getProductid();
JSONArray items3;
if (!flag) {
// wishlist.setBackgroundResource(R.drawable.wishnew);
flag = true;
String channel = wishshared.getString(Constants.productid, "['']");
JSONArray items;
String wishitem;
if (TextUtils.isEmpty(channel)) {
items = new JSONArray();
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
editors.apply();
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems", Toast.LENGTH_LONG).show();
flag = false;
} else {
try {
Boolean found = false;
items = new JSONArray(channel);
for (int x = 0; x < items.length(); x++) {
if (pos.equalsIgnoreCase(items.getString(x))) {
found = true;
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems1", Toast.LENGTH_LONG).show();
}
}
if (!found) {
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
removeAt(getAdapterPosition());
Toast.makeText(context, Constants.productid, Toast.LENGTH_LONG).show();
Log.i(Constants.productid, "wishitems");
}
editors.apply();
flag = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
Intent list = new Intent(view.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
} else {
removeAt(getAdapterPosition());
Intent list = new Intent(view.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
}
} else {
pos = cartlistadp.get(getAdapterPosition()).getProductid();
if (!flag) {
// wishlist.setBackgroundResource(R.drawable.wishnew);
flag = true;
String channel = wishshared.getString(Constants.productid, "['']");
JSONArray items;
String wishitem;
if (TextUtils.isEmpty(channel)) {
items = new JSONArray();
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
editors.apply();
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems", Toast.LENGTH_LONG).show();
flag = false;
} else {
try {
Boolean found = false;
items = new JSONArray(channel);
for (int x = 0; x < items.length(); x++) {
if (pos.equalsIgnoreCase(items.getString(x))) {
found = true;
removeAt(getAdapterPosition());
}
}
if (!found) {
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
removeAt(getAdapterPosition());
Log.i(Constants.productid, "wishitems");
}
editors.apply();
flag = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
removeAt(getAdapterPosition());
}
}
}
});
}
}
public class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) {}
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
private class MyTextWatcher implements TextWatcher {
private View view;
private EditText editText;
private int position;
//private int position;
private MyTextWatcher(View view, int position) {
this.view = view;
this.position = position;
// this.position = adapterPosition;
// cartlistadp.get(position).getQty() = Integer.parseInt((Caption.getText().toString()));
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//do nothing
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// EditText qtyView = (EditText) view.findViewById(R.id.quantity);
Log.i("editextpostion", String.valueOf(position));
}
public void afterTextChanged(Editable s) {
DecimalFormat df = new DecimalFormat("0");
String qtyString = s.toString();
int quantity = qtyString.equals("") ? 0 : Integer.valueOf(qtyString);
String quty = String.valueOf(quantity);
EditText qtyView = (EditText) view.findViewById(R.id.quantity);
CartItemoriginal product = (CartItemoriginal) qtyView.getTag();
// int position = (int) view.qtyView.getTag();
Log.d("postion is qtytag", "Position is: " + product);
qtyView.setFilters(new InputFilter[] {
new InputFilterMinMax(product.getMinquantity(), product.getMaxquantity())
});
if (product.getQty() != quantity) {
Double currPrice = product.getExt();
Double price = Double.parseDouble(product.getPrice());
int maxaty = Integer.parseInt(product.getMaxquantity());
int minqty = Integer.parseInt(product.getMinquantity());
if (quantity < maxaty) {
extPrice = quantity * price;
} else {
Toast.makeText(context, "Sorry" + " " + " " + "we are shipping only" + " " + " " + maxaty + " " + " " + "unit of quantity", Toast.LENGTH_LONG).show();
}
Double priceDiff = Double.valueOf(df.format(extPrice - currPrice));
product.setQty(quantity);
product.setExt(extPrice);
TextView ext = (TextView) view.findViewById(R.id.CartAmt);
if (product.getQty() != 0) {
ext.setText("Rs." + " " + df.format(product.getExt()));
} else {
ext.setText("0");
}
if (product.getQty() != 0) {
qtyView.setText(String.valueOf(product.getQty()));
} else {
qtyView.setText("");
}
JSONArray test = new JSONArray();
JSONArray test1 = new JSONArray();
JSONArray test2 = new JSONArray();
JSONArray items = null;
JSONArray itemsQty = null;
test1.put("0");
test2.put("0");
test.put(test1);
test.put(test2);
JSONArray listitems = null;
//String Sharedqty= String.valueOf(cartlistadp.get(getAdapterPosition()).getQty());
String channel = (shared.getString(Constants.cartid, String.valueOf(test)));
try {
listitems = new JSONArray(channel);
itemsQty = listitems.getJSONArray(1);
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (itemsQty != null) {
itemsQty.put(position + 1, qtyString);
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (listitems != null) {
listitems.put(1, itemsQty);
}
} catch (JSONException e) {
e.printStackTrace();
}
QutId.putString(Constants.cartid, String.valueOf(listitems));
QutId.apply();
Toast.makeText(context, String.valueOf(listitems), Toast.LENGTH_SHORT).show();
totalPrice();
}
return;
}
private void totalPrice() {
int price = 0;
for (int j = 0; j < cartlistadp.size(); j++) {
price += Integer.parseInt(cartlistadp.get(j).getPrice()) * (cartlistadp.get(j).getQty());
String totalprice = String.valueOf(price);
String count = String.valueOf(cartlistadp.size());
CartItems.Totalamt.setText(totalprice);
CartItems.cartcount.setText("(" + count + ")");
CartItems.carttotalcount.setText("(" + count + ")");
}
}
public void updatePosition(int position) {
this.position = position;
}
}
}
Thanks in Advance.
For sorting you need to Collection.sort method of Java and also you need to implement comparable interface for define your comparison.
CartItemoriginal implements Comparable {
public int compareTo(Object obj) { } }
Updated
public class CartItemoriginal implements Comparable<CartItemoriginal > {
private Float val;
private String id;
public CartItemoriginal (Float val, String id){
this.val = val;
this.id = id;
}
#Override
public int compareTo(ToSort f) {
if (val.floatValue() > f.val.floatValue()) {
return 1;
}
else if (val.floatValue() < f.val.floatValue()) {
return -1;
}
else {
return 0;
}
}
#Override
public String toString(){
return this.id;
}
}
and use
Collections.sort(sortList);

Using AlertDialog.Builder to build custom AlertDialog class

I have a Class FoodDialog that extends AlertDialog that I have customized to how I would like it to look.
I am now wanting to edit the positive/negative buttons using an AlertDialog.Builder, however, when I attempt to build an instance of FoodDialog using a builder, I am facing an 'Incompatible types' error where the builder is asking for AlertDialog instead I am providing it with an extension of AlertDialog - is there a way around this?
If not, is there a way I can edit the positive/negative buttons of my custom AlertDialog class FoodDialog?
Below is my FoodDialog class. The yes/no buttons I have there are ones I have created myself, but I would like the ones that are part of the AlertDialog.Builder to appear instead as these buttons get pushed out of sight when the soft keyboard appears:
public class FoodDialog extends AlertDialog implements OnClickListener {
private TextView foodNameTextView, foodDescTextView, foodPortionTextView, catTextView, qtyText, cal, fat, sFat, carb, sug, prot, salt, imageTxt,
measureText;
private EditText foodQty;
private ImageView foodImage;
private ImageButton yesBtn, noBtn;
private int foodID, totalCal;
private Bitmap image;
private String user, portionType, foodName, foodDesc, cat, totalCalString, totalFatString,
totalSFatString, totalCarbString, totalSugString, totalProtString, totalSaltString, portionBaseString;
private double totalFat, totalSFat, totalCarb, totalSug, totalProt, totalSalt, portionBase;
private Food food;
private Portion portion;
private Nutrients nutrients;
private PortionType pType;
private DBHandler db;
public FoodDialog(Context context){
super(context);
}
public FoodDialog(Context context, int foodID, String imgLocation, final String user) {
super(context, android.R.style.Theme_Holo_Light_Dialog);
this.setTitle("Confirm?");
setContentView(R.layout.dialog_layout);
this.foodID = foodID;
this.user = user;
db = new DBHandler(context);
food = db.getFoodByID(foodID, user);
portion = db.getPortionByFoodID(foodID);
nutrients = db.getNutrientsByFoodIDAndPortionType(foodID, portion.getPortionType());
pType = db.getPortionTypeByName(portion.getPortionType());
//getting object attributes
portionType = portion.getPortionType();
portionBase = portion.getPortionBase();
//food
foodName = food.getName();
foodDesc = food.getDesc();
cat = food.getCat();
//nutrients
totalCal = nutrients.getCal();
totalFat = nutrients.getFat();
totalSFat = nutrients.getSFat();
totalCarb = nutrients.getCarb();
totalSug = nutrients.getSug();
totalProt = nutrients.getProt();
totalSalt = nutrients.getSalt();
//converting to string
totalCalString = String.valueOf(totalCal);
if (totalFat % 1 == 0) {
totalFatString = String.format("%.0f", totalFat);
} else {
totalFatString = String.valueOf(totalFat);
}
if (totalSFat % 1 == 0) {
totalSFatString = String.format("%.0f", totalSFat);
} else {
totalSFatString = String.valueOf(totalSFat);
}
if (totalCarb % 1 == 0) {
totalCarbString = String.format("%.0f", totalCarb);
} else {
totalCarbString = String.valueOf(totalCarb);
}
if (totalSug % 1 == 0) {
totalSugString = String.format("%.0f", totalSug);
} else {
totalSugString = String.valueOf(totalSug);
}
if (totalProt % 1 == 0) {
totalProtString = String.format("%.0f", totalProt);
} else {
totalProtString = String.valueOf(totalProt);
}
if (totalSalt % 1 == 0) {
totalSaltString = String.format("%.0f", totalSalt);
} else {
totalSaltString = String.valueOf(totalSalt);
}
if (portionBase % 1 == 0) {
portionBaseString = String.format("%.0f", portionBase);
} else {
portionBaseString = String.valueOf(portionBase);
}
//textviews
foodNameTextView = (TextView) findViewById(R.id.dialogName);
foodNameTextView.setText(foodName);
foodDescTextView = (TextView) findViewById(R.id.dialogDesc);
foodDescTextView.setText(foodDesc);
foodPortionTextView = (TextView) findViewById(R.id.dialogPortion);
foodPortionTextView.setText("Values based per " + portionBase + " " + portionType);
catTextView = (TextView) findViewById(R.id.dialogCat);
catTextView.setText(cat);
measureText = (TextView) findViewById(R.id.dialogMeasure);
measureText.setText(portionType);
qtyText = (TextView) findViewById(R.id.dialogQtyText);
imageTxt = (TextView) findViewById(R.id.dialogImageText);
cal = (TextView) findViewById(R.id.dialogCal);
cal.setText(totalCalString);
fat = (TextView) findViewById(R.id.dialogFat);
fat.setText(totalFatString + "g");
sFat = (TextView) findViewById(R.id.dialogSFat);
sFat.setText(totalSFatString + "g");
carb = (TextView) findViewById(R.id.dialogCarb);
carb.setText(totalCarbString + "g");
sug = (TextView) findViewById(R.id.dialogSug);
sug.setText(totalSugString + "g");
prot = (TextView) findViewById(R.id.dialogProt);
prot.setText(totalProtString + "g");
salt = (TextView) findViewById(R.id.dialogSalt);
salt.setText(totalSaltString + "g");
//img
foodImage = (ImageView) findViewById(R.id.dialogImage);
imgLocation = food.getImgURL();
image = BitmapFactory.decodeFile(imgLocation);
foodImage.setImageBitmap(image);
if (imgLocation.equals("nourl")) {
imageTxt.setText("No Image");
}
//edit tex
foodQty = (EditText) findViewById(R.id.dialogQty);
//adjusting edittext
foodQty.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
foodQty.setFilters(new InputFilter[]{
new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) {
int beforeDecimal = 4, afterDecimal = 3;
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String temp = foodQty.getText() + source.toString();
if (temp.equals(".")) {
return "0.";
} else if (temp.toString().indexOf(".") == -1) {
// no decimal point placed yet
if (temp.length() > beforeDecimal) {
return "";
}
} else {
temp = temp.substring(temp.indexOf(".") + 1);
if (temp.length() > afterDecimal) {
return "";
}
}
return super.filter(source, start, end, dest, dstart, dend);
}
}
});
foodQty.setText(portionBaseString);
//btns
yesBtn = (ImageButton) findViewById(R.id.yesBtn);
noBtn = (ImageButton) findViewById(R.id.noBtn);
Bitmap tick = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_tick);
Bitmap cross = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_cross);
yesBtn.setImageBitmap(tick);
noBtn.setImageBitmap(cross);
yesBtn.setOnClickListener(this);
noBtn.setOnClickListener(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
#Override
public void onClick(View v) {
if (v == yesBtn) {
SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
String date = currentDate.format(new Date());
String time = currentTime.format(new Date());
double qty = 0;
//get quantity amount
// if (portionMeasure.equals("singles")) {
//qty = foodQty.getValue();
// } else {
if (foodQty.getText().length() != 0) {
qty = Double.valueOf(foodQty.getText().toString());
} else {
qty = 0;
}
// }
if (qty == 0 || String.valueOf(qty) == "") {
Toast.makeText(getContext(), "Please enter an amount", Toast.LENGTH_SHORT).show();
} else {
//create new intake
Intake intake = new Intake(0, foodID, portionType, qty, date, time);
//record it and increment food used value
db.recordIntake(intake, user);
db.incrementUsedCount(intake.getFoodID(), 1);
db.close();
cancel();
Toast.makeText(getContext(), foodName + " recorded", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("What next?");
builder.setItems(new CharSequence[]
{"Record another food intake..", "Main Menu..", "View Stats.."},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
cancel();
break;
case 1:
Intent main = new Intent(getContext(), ProfileActivity.class);
getContext().startActivity(main);
break;
case 2:
Intent stats = new Intent(getContext(), StatsActivity.class);
getContext().startActivity(stats);
break;
}
}
});
AlertDialog choose = builder.create();
choose.show();
}
} else if (v == noBtn) {
cancel();
}
}
}
You can catch your buttons click listener as follows:
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//yes button click code here
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//no button click code here
}
});
You can use the logcat to see if your listener are being fired.

Cart Count increment & decrement while clicking button

I populates cart items into the list using cursor adapter. My ListView item has
Price TextView
Product Name TextView
Count TextView
Increment Button
Decrement Buttton
When I click the increment / decrement button the value is incremented/ decremented in a certain condition of AFTER TOUCHING THE LISTVIEW ROW,otherwise the count is not changed.
In some case, if I click the 1st row increment button ,item count is incremented in 2nd row.
NOTE:
1. I am populating List using Cursor Adapter.
2. Using Increment & Decrement clicklistener in activity class.
Here is my code:
cartList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> parent, View itemView, final int position, final long rowId) {
txt_cartProduct = (TextView) itemView.findViewById(R.id.cartProduct);
txt_cartQuantity = (TextView) itemView.findViewById(R.id.cartQuantity);
txt_cartPrice = (TextView) itemView.findViewById(R.id.cartPrice);
txt_cartPriceDum = (TextView) itemView.findViewById(R.id.cartPriceDum);
txt_cartCount = (TextView) itemView.findViewById(R.id.cartCount);
img_ivDecrease = (ImageView) itemView.findViewById(R.id.ivDecrease);
img_ivIncrease = (ImageView) itemView.findViewById(R.id.ivIncrease);
but_addTowish = (Button) itemView.findViewById(R.id.addTowish);
but_remove = (Button) itemView.findViewById(R.id.remove);
img_ivIncrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strPrice = txt_cartPrice.getText().toString();
price = Integer.parseInt(strPrice);
int counter = 0;
try {
counter = Integer.parseInt(txt_cartCount.getText().toString());
} catch (NumberFormatException e) {
e.printStackTrace();
}
counter++;
if (counter > 0) {
txt_cartCount.setText(Integer.toString(counter));
txt_cartPrice.setVisibility(View.GONE);
txt_cartPriceDum.setVisibility(View.VISIBLE);
quantity = txt_cartCount.getText().toString();
total = (Integer.parseInt(quantity)) * (price);
netA = String.valueOf(total);
sum += price;
if (sum == 0) {
netAmount = Integer.parseInt(txt_cartPriceDum.getText().toString());
}
netAmount = sum;
Log.e("Sum is", String.valueOf(sum));
txt_cartPriceDum.setText(String.valueOf(total));
cartCount = Integer.parseInt(quantity);
Toast.makeText(context, "netAmount" + netAmount + "\n" + "Total" + total, Toast.LENGTH_SHORT).show();
if (counter == 1) {
cartPrice = price;
cartSum = sum;
}
if (counter == 0) {
cartPrice = 0;
cartSum = 0;
cartCount = 0;
Toast.makeText(context, "Minimum Item is 1", Toast.LENGTH_SHORT).show();
}
int count_check = 1;
if (count_check >= position) {
count_check++;
} else if (count_check == 0) {
Toast.makeText(context, "Minimum Item is 1", Toast.LENGTH_SHORT).show();
}
}
}
});
img_ivDecrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strPrice = txt_cartPrice.getText().toString();
price = Integer.parseInt(strPrice);
int counter = 0;
try {
counter = Integer.parseInt(txt_cartCount.getText().toString());
} catch (NumberFormatException e) {
e.printStackTrace();
}
counter--;
if (counter > 0) {
txt_cartCount.setText(Integer.toString(counter));
txt_cartPrice.setVisibility(View.GONE);
txt_cartPriceDum.setVisibility(View.VISIBLE);
quantity = txt_cartCount.getText().toString();
total = (Integer.parseInt(quantity)) * (price);
netA = String.valueOf(total);
sum -= price;
if (sum == 0) {
netAmount = Integer.parseInt(txt_cartPriceDum.getText().toString());
}
Log.e("Sum - is", String.valueOf(sum));
txt_cartPriceDum.setText(String.valueOf(total));
cartCount = Integer.parseInt(quantity);
Toast.makeText(context, "netAmount" + netAmount + "\n" + "Total" + total, Toast.LENGTH_SHORT).show();
if (counter == 1) {
cartPrice = price;
cartSum = sum;
}
if (counter == 0) {
cartPrice = 0;
cartSum = 0;
cartCount = 0;
}
}
}
});
}
});
You can use setTag() and getTag() methods for saving the counter value in each list item.
Refer this answer for more details.

Android data storage and retrieving

I developed an android application in which a users provides 6 pieces of information in 6 separate text boxes (information such as first name, last name, middle name, mobile number email id etc)
When the user presses a Save button, I need to store this information and be able to recall this information when the Recall button is pressed.
What is the next step to accomplish this
My code so far is below:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DatePicker date = (DatePicker) findViewById (R.id.datePicker1);
final TextView tv1 = (TextView) findViewById (R.id.textView88);
final TextView tv2 = (TextView) findViewById (R.id.textView89);
final TextView tv3 = (TextView) findViewById (R.id.textView90);
final TextView tv4 = (TextView) findViewById (R.id.textView91);
final TextView tv5 = (TextView) findViewById (R.id.textView92);
final TextView tv6 = (TextView) findViewById (R.id.textView93);
final TextView tv7 = (TextView) findViewById (R.id.textView94);
date.init(date.getYear(), date.getMonth(), date.getDayOfMonth(),new OnDateChangedListener()
{
#Override
public void onDateChanged(DatePicker arg0, int arg1, int arg2, int arg3)
{
// TODO Auto-generated method stub
String date=Integer.toString(arg3);
String month=Integer.toString(arg2);
String year=Integer.toString(arg1);
tv1.setText(date+ month+1 +year);
tv2.setText(month+1 + date);
tv3.setText(year);
tv4.setText(month+1);
tv5.setText(date);
tv6.setText(date + year);
}
});}
public void sum(View v)
{
long sum1=0;
long sum2=0;
long sum3=0;
long sum4=0;
long sum5=0;
long sum6=0;
long sum7=0;
long sum8=0;
long sum=0;
long sum11=0;
long sum12=0;
long sum13=0;
long sum14=0;
long sum100=0;
EditText et1 = (EditText) findViewById (R.id.editText1);
EditText et2 = (EditText) findViewById (R.id.editText2);
EditText et3 = (EditText) findViewById (R.id.editText3);
EditText et4 = (EditText) findViewById (R.id.editText4);
EditText et5 = (EditText) findViewById (R.id.editText5);
EditText et6 = (EditText) findViewById (R.id.editText6);
final DatePicker date = (DatePicker) findViewById (R.id.datePicker1);
final TextView tv1 = (TextView) findViewById (R.id.textView88);
final TextView tv2 = (TextView) findViewById (R.id.textView89);
final TextView tv3 = (TextView) findViewById (R.id.textView90);
final TextView tv4 = (TextView) findViewById (R.id.textView91);
final TextView tv5 = (TextView) findViewById (R.id.textView92);
final TextView tv6 = (TextView) findViewById (R.id.textView93);
final TextView tv7 = (TextView) findViewById (R.id.textView94);
sum1=getSum(et1.getText().toString() + et2.getText().toString() + et3.getText().toString() + et4.getText().toString());
sum2=getSum1(et1.getText().toString() + et2.getText().toString() + et3.getText().toString() + et4.getText().toString());
sum3=getSum2(tv1.getText().toString());
/*sum4=getSum3(tv2.getText().toString());*/
sum5=getSum4(tv3.getText().toString());
sum6=getSum5(tv4.getText().toString());
sum8=getSum7(tv5.getText().toString());
String yearf = tv3.getText().toString();
int yearb = Integer.valueOf(yearf);
int val = 2013 - yearb;
long val1 = sum3;
/*int val2 = Integer.valueOf(val1);*/
long val3 = 36 - val1;
int val4 = 9;
long val5 = val3 + val4;
long val6 = val5 + val4;
long val7 = val6 + 50;
sum = getSum3(tv2.getText().toString()) + getSum8(tv6.getText().toString());
sum100 = getSum4(tv3.getText().toString()) + getSum5(tv4.getText().toString());
if (val <= val3)
{
sum4=getSum3(tv2.getText().toString());
}
else if ((val <= val5) && (val > val3))
{
sum4=getSum8(tv6.getText().toString());
}
else if ((val<=val6) && (val > val5) && (val > val3))
{
/*sum = getSum3(tv2.getText().toString()) + getSum8(tv6.getText().toString());*/
sum4=getSum9(Integer.toString((int) sum));
}
else
{
sum4=getSum9(Integer.toString((int) sum100));
}
if (val <= val3)
{
if (sum8>sum6)
{
sum7 = (sum8 - sum6);
}
else
{
sum7 = (sum6 - sum8);
}
}
else if ((val <= val5) && (val > val3))
{
if(sum5>sum8)
{
sum7=(sum5 - sum8);
}
else
{
sum7 = (sum8 - sum5);
}
}
else if ((val<=val6) && (val > val5) && (val > val3))
{
sum11 = (sum5 - sum8);
sum12 = (sum8 - sum5);
sum13 = (sum6 - sum8);
sum14 = (sum8 - sum6);
if ((sum11 > sum12) && (sum13 > sum14))
{
if (sum11 > sum13)
{
sum7 = sum11 - sum13;
}
else
{
sum7 = sum13 - sum11;
}
}
else if ((sum12 > sum11) && (sum13 > sum14))
{
if (sum12 > sum13)
{
sum7 = sum12 - sum13;
}
else
{
sum7 = sum13 - sum12;
}
}
else if ((sum11 > sum12) && (sum14 > sum13))
{
if (sum11 > sum14)
{
sum7 = sum11 - sum14;
}
else
{
sum7 = sum14 - sum11;
}
}
else if ((sum12 > sum11) && (sum14 > sum13))
{
if (sum12 > sum14)
{
sum7 = sum12 - sum14;
}
else
{
sum7 = sum14 - sum12;
}
}
}
else
{
if (sum5>sum6)
{
sum7 = (sum5 - sum6);
}
else
{
sum7 = (sum6 - sum5);
}
}
String edtxt1 = et1.getText().toString();
String edtxt4 = et4.getText().toString();
String edtxt5 = et5.getText().toString();
String edtxt6 = et6.getText().toString();
if(edtxt1.equals(""))
{
Toast.makeText(getApplicationContext(),"First Name should not be left blank, Please enter your First Name ", Toast.LENGTH_LONG).show();
}
else if(edtxt4.equals(""))
{
Toast.makeText(getApplicationContext(),"Last Name should not be left blank, Please enter your Last Name ", Toast.LENGTH_LONG).show();
}
else if(edtxt5.equals(""))
{
Toast.makeText(getApplicationContext(),"Mobile Number should not be left blank, Please enter your Mobile Number ", Toast.LENGTH_LONG).show();
}
else if(edtxt6.equals(""))
{
Toast.makeText(getApplicationContext(),"E-Mail id should not be left blank, Please enter your E-Mail id ", Toast.LENGTH_LONG).show();
}
else{
Intent i = new Intent(this, result.class);
i.putExtra("name", sum1 + "");
i.putExtra("name1", sum2 + "");
i.putExtra("name2", sum3 + "");
i.putExtra("name3", sum4 + "");
i.putExtra("name4", sum7 + "");
startActivity(i);
}
public long getSum(String text)
{
// TODO Auto-generated method stub
long sum1 = 0;
char[] name = new char[text.length()];
name = text.toCharArray();
for(int i=0; i<text.length(); i++)
{
sum1 += value( name[i] );
}
while (sum1>9)
{
sum1 = findDigitSum(sum1);
}
return sum1;
}
public long getSum1(String text)
{
// TODO Auto-generated method stub
long sum2 = 0;
char[] name1 = new char[text.length()];
name1 = text.toCharArray();
for(int i=0; i<text.length(); i++)
{
sum2 += value1( name1[i] );
}
while (sum2>9)
{
sum2 = findDigitSum(sum2);
}
return sum2;
}
db = openOrCreateDatabase("MyDBI", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS TABLE1 ();");
You can create database using this code
db.execSQL("INSERT INTO TABLE1 VALUES('"+fname"');
And values can be inserted to this database using this code.
A tablelayout can be created and the saved details can be displayed in this tablelayout. Give clickable option and clicking all the details can be transferred using intents to the previous activity.

Can't get same value when implementing reset button with spinner and edit text

I have 10 spinner and 10 edit text (user are able to let several spinner and edit text blank), and I also have 2 button to sum value from the selected spinner object and edit text. It's successful to sum the value, but when I use my reset button to get back to the initial state when the app is first launched, I got the problem. The result is wrong, I got the value from the first operation even though I have set it back to the default. This is my code for the reset button
hapus.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
qty1.setText(null);
qty2.setText(null);
qty3.setText(null);
qty4.setText(null);
qty5.setText(null);
qty6.setText(null);
qty7.setText(null);
qty8.setText(null);
qty9.setText(null);
qty10.setText(null);
spin1.setSelection(0);
spin2.setSelection(0);
spin3.setSelection(0);
spin4.setSelection(0);
spin5.setSelection(0);
spin6.setSelection(0);
spin7.setSelection(0);
spin8.setSelection(0);
spin9.setSelection(0);
spin10.setSelection(0);
sum.setText(null);
hasil = 0;
}
});
And this is a part of my code for the spinner and sum operation
spin8.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View selectedItem, int pos, long id)
{
Object item = parent.getItemAtPosition(pos);
value8 = item.toString();
if (item.equals("null"))
{
hrg8 = 0;
}
else if (item.equals("Soto Istimewa"))
{
hrg8 = 24000;
}
else if (item.equals("Soto Biasa"))
{
hrg8 = 17000;
}
else if (item.equals("Nasi Putih"))
{
hrg8 = 4000;
}
else if (item.equals("Emping"))
{
hrg8 = 2000;
}
else if (item.equals("Kerupuk"))
{
hrg8 = 1000;
}
else if (item.equals("Es Teh"))
{
hrg8 = 2000;
}
else if (item.equals("Es Teh Manis"))
{
hrg8 = 3000;
}
else if (item.equals("Es Teh Botol"))
{
hrg8 = 5000;
}
else if (item.equals("Teh Botol Dingin"))
{
hrg8 = 3000;
}
else if (item.equals("Air Jeruk Panas"))
{
hrg8 = 7000;
}
else if (item.equals("Air Jeruk Dingin"))
{
hrg8 = 7000;
}
else if (item.equals("Aqua"))
{
hrg8 = 3000;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
spin9.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View selectedItem, int pos, long id)
{
Object item = parent.getItemAtPosition(pos);
value9 = item.toString();
if (item.equals("null"))
{
hrg9 = 0;
}
else if (item.equals("Soto Istimewa"))
{
hrg9 = 24000;
}
else if (item.equals("Soto Biasa"))
{
hrg9 = 17000;
}
else if (item.equals("Nasi Putih"))
{
hrg9 = 4000;
}
else if (item.equals("Emping"))
{
hrg9 = 2000;
}
else if (item.equals("Kerupuk"))
{
hrg9 = 1000;
}
else if (item.equals("Es Teh"))
{
hrg9 = 2000;
}
else if (item.equals("Es Teh Manis"))
{
hrg9 = 3000;
}
else if (item.equals("Es Teh Botol"))
{
hrg9 = 5000;
}
else if (item.equals("Teh Botol Dingin"))
{
hrg9 = 3000;
}
else if (item.equals("Air Jeruk Panas"))
{
hrg9 = 7000;
}
else if (item.equals("Air Jeruk Dingin"))
{
hrg9 = 7000;
}
else if (item.equals("Aqua"))
{
hrg9 = 3000;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
spin10.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View selectedItem, int pos, long id)
{
Object item = parent.getItemAtPosition(pos);
value10 = item.toString();
if (item.equals("null"))
{
hrg10 = 0;
}
else if (item.equals("Soto Istimewa"))
{
hrg10 = 24000;
}
else if (item.equals("Soto Biasa"))
{
hrg10 = 17000;
}
else if (item.equals("Nasi Putih"))
{
hrg10 = 4000;
}
else if (item.equals("Emping"))
{
hrg10 = 2000;
}
else if (item.equals("Kerupuk"))
{
hrg10 = 1000;
}
else if (item.equals("Es Teh"))
{
hrg10 = 2000;
}
else if (item.equals("Es Teh Manis"))
{
hrg10 = 3000;
}
else if (item.equals("Es Teh Botol"))
{
hrg10 = 5000;
}
else if (item.equals("Teh Botol Dingin"))
{
hrg10 = 3000;
}
else if (item.equals("Air Jeruk Panas"))
{
hrg10 = 7000;
}
else if (item.equals("Air Jeruk Dingin"))
{
hrg10 = 7000;
}
else if (item.equals("Aqua"))
{
hrg10 = 3000;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
hitung.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
if (qty1.getText().toString() != null && !(qty1.getText().toString().equals("")))
{
jml1 = Integer.parseInt(qty1.getText().toString());
item1 = hrg1 * jml1;
}
else
{
jml1 = 0;
}
if (qty2.getText().toString() != null && !(qty2.getText().toString().equals("")))
{
jml2 = Integer.parseInt(qty2.getText().toString());
item2 = hrg2 * jml2;
}
else
{
jml2 = 0;
}
if (qty3.getText().toString() != null && !(qty3.getText().toString().equals("")))
{
jml3 = Integer.parseInt(qty3.getText().toString());
item3 = hrg3 * jml3;
}
else
{
jml3 = 0;
}
if (qty4.getText().toString() != null && !(qty4.getText().toString().equals("")))
{
jml4 = Integer.parseInt(qty4.getText().toString());
item4 = hrg4 * jml4;
}
else
{
jml4 = 0;
}
if (qty5.getText().toString() != null && !(qty5.getText().toString().equals("")))
{
jml5 = Integer.parseInt(qty5.getText().toString());
item5 = hrg5 * jml5;
}
else
{
jml5 = 0;
}
if (qty6.getText().toString() != null && !(qty6.getText().toString().equals("")))
{
jml6 = Integer.parseInt(qty6.getText().toString());
item6 = hrg6 * jml6;
}
else
{
jml6 = 0;
}
if (qty7.getText().toString() != null && !(qty7.getText().toString().equals("")))
{
jml7 = Integer.parseInt(qty7.getText().toString());
item7 = hrg7 * jml7;
}
else
{
jml7 = 0;
}
if (qty8.getText().toString() != null && !(qty8.getText().toString().equals("")))
{
jml8 = Integer.parseInt(qty8.getText().toString());
item8 = hrg8 * jml8;
}
else
{
jml8 = 0;
}
if (qty9.getText().toString() != null && !(qty9.getText().toString().equals("")))
{
jml9 = Integer.parseInt(qty9.getText().toString());
item9 = hrg9 * jml9;
}
else
{
jml9 = 0;
}
if (qty10.getText().toString() != null && !(qty10.getText().toString().equals("")))
{
jml10 = Integer.parseInt(qty10.getText().toString());
item10 = hrg10 * jml10;
}
else
{
jml10 = 0;
}
hasil = item1 + item2 + item3 + item4 + item5 + item6 + item7 + item8 + item9 + item10;
Toast.makeText(getApplicationContext(), "Rp. " + hasil, Toast.LENGTH_LONG).show();
sum.setText("Rp. " + Integer.toString(hasil));
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Quantity can't be empty. Please type item quantity", Toast.LENGTH_LONG).show();
}
}
});
Any help will be appreciate, thanks
You are trying to use null as a String:
if (item.equals("null"))
It should be:
if (item == null)
Also the default value of an Spinner or EditText is an empty String (i.e. "") not null. I believe you should use .setText(""); when you reset the values, so really that first if statement should be:
if (item.isEmpty()) // or item.equals("")
Lastly do you have 10 OnItemSelectedListeners that contains 80-90% of the same code? If so your should write one generic listener and use parent.getId() to determine which value to set.

Categories

Resources