Reputation: 111
I'm new in Android. I'm trying to create an e-commerce app. Currently, I'm creating add-to-cart activity
. So, I've managed to add the item to cart and display in CartActivity
. But the problem is, I don't know how to get the price and calculate the total price of all item. When I delete the item(i use onSwiped
) the price not decreasing.
CartActivity
public class CartActivity extends AppCompatActivity implements
RecyclerItemTouchHelper.RecyclerItemTouchHelperListener {
private float totalcost=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onDataChange: found a post id: babyyywhuu " + book_id);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
// Called when a user swipes left or right on a ViewHolder
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
int position = viewHolder.getAdapterPosition(); // this is how you can get the position
Book book= mAdapter.getItem(position); // You will have your own class ofcourse.
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("carts")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(book.getBook_id())
.removeValue();
}
}).attachToRecyclerView(recyclerView);
init();
}
private void init(){
Log.d(TAG, "init: initializing.");
cartList = new ArrayList<>();
setupPostsList();
//reference for listening when items are added or removed from the watch list
mDatabaseRef = FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.node_carts))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//set the listener to the reference
mDatabaseRef.addValueEventListener(mLisenter);
}
private void getWatchListIds(){
Log.d(TAG, "getWatchListIds: getting users watch list.");
if(cartList != null){
cartList.clear();
}
if(mPostsIds != null){
mPostsIds.clear();
}
mPostsIds = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child(getString(R.string.node_carts))
.orderByKey()
.equalTo(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getChildren().iterator().hasNext()){
DataSnapshot singleSnapshot = dataSnapshot.getChildren().iterator().next();
for(DataSnapshot snapshot: singleSnapshot.getChildren()){
String id = snapshot.child(getString(R.string.field_book_id)).getValue().toString();
Log.d(TAG, "onDataChange: found a post id: " + id);
mPostsIds.add(id);
}
getPosts();
}else{
getPosts();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void getPosts(){
if(mPostsIds.size() > 0){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
for(int i = 0; i < mPostsIds.size(); i++){
Log.d(TAG, "getPosts: getting post information for: " + mPostsIds.get(i));
Query query = reference.child(getString(R.string.node_books))
.orderByKey()
.equalTo(mPostsIds.get(i));
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
DataSnapshot singleSnapshot = dataSnapshot.getChildren().iterator().next();
Book book = singleSnapshot.getValue(Book.class);
Log.d(TAG, "onDataChange: found a post: " + book.getTitle());
cartList.add(book);
mAdapter = new CartListAdapter (CartActivity.this, cartList);
recyclerView.setAdapter(mAdapter);
here----> totalcost += Float.parseFloat(book.getPrice());
String totPrice = Float.toString(totalcost);
TextView totPrice = findViewById(R.id.totalPrice);
totPrice.setText(totPrice);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
@Override
public void onResume() {
super.onResume();
cartList = new ArrayList<>();
}
/**
* callback when recycler view is swiped
* item will be removed on swiped
* undo option will be provided in snackbar to restore the item
*/
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position) {
if (viewHolder instanceof CartListAdapter.MyViewHolder) {
// get the removed item name to display it in snack bar
String name = cartList.get(viewHolder.getAdapterPosition()).getTitle();
// backup of removed item for undo purpose
final Book deletedItem = cartList.get(viewHolder.getAdapterPosition());
final int deletedIndex = viewHolder.getAdapterPosition();
// remove the item from recycler view
mAdapter.removeItem(viewHolder.getAdapterPosition());
// showing snack bar with Undo option
Snackbar snackbar = Snackbar
.make(linearlayour, name + " removed from cart!", Snackbar.LENGTH_LONG);
snackbar.setAction("UNDO", new View.OnClickListener() {
@Override
public void onClick(View view) {
// undo is selected, restore the deleted item
mAdapter.restoreItem(deletedItem, deletedIndex);
}
});
snackbar.setActionTextColor(Color.YELLOW);
snackbar.show();
}
}
I've tried calculate it inside the getPosts()
but I know it is completely wrong because the price keep on increasing. Do I have to create method to increase/decrease the method? Do you have any solutions to this? Thank you for your time.
Upvotes: 1
Views: 5488
Reputation: 31
There are 4 Cases where you have to update your price:-
Just create a new function and recalculate the total price, set to the text view and call just after adapter notifies or update adapter.
Upvotes: 1
Reputation: 6073
when you swipe to delete item from cart , try to get the item price and then subtract it from total amount :
int total_price = Integer.parseInt(totprice.getText().toString()) - theRemovedItemPrice ;
totprice.setText(String.valueOf(total_price) ;
Upvotes: 0