title: How to calculate total price when add/delete item in Android Studio
body: <p>I'm new in <strong>Android</strong>. I'm trying to create an e-commerce app. Currently, I'm creating add-to-cart <code>activity</code>. So, I've managed to add the item to cart and display in <code>CartActivity</code>. 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 <code>onSwiped</code>) the price not decreasing. </p>
  
  <p><em>CartActivity</em></p>
  
  <pre><code>  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&lt;&gt;();
      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&lt;&gt;();
      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() &gt; 0){
          DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
  
          for(int i  = 0; i &lt; 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----&gt;           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&lt;&gt;();
  
  
  }
  
  /**
   * 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();
      }
  }
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/GWKiK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GWKiK.png" alt="enter image description here"></a></p>
  
  <p>I've tried calculate it inside the <code>getPosts()</code> 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.</p>