Search code examples
androidlistviewsumonactivityresult

Sum up value from OnActivityResult


I have a listview in Activity A. I want to sum up the total amount which are return from Activity B to Activity A, but I have no idea on how to add them up.

 double sum =0;

public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Activity B and populate ListView A
     if (resultCode == RESULT_OK) {
         if (requestCode == PROJECT_REQUEST_CODE) {
             double ReceiveAmount = data.getDoubleExtra("amount",0);
             sum = + ReceiveAmount;
            totalAmount.setText(sum+")
             }
         }
     }
 }

Assume in Activity B I return amount 5, then I go to Activity B again and return value 10. I want the toast display value 15 instead of always 5.

Edit

   @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Activity B and populate ListView A
            if (resultCode == RESULT_OK) {
                if (requestCode == PROJECT_REQUEST_CODE) {
                   double ReceiveAmount = data.getDoubleExtra("amount",0);
                    sum += ReceiveAmount;
                    if (mClickedPosition == -1) {  // if icon clicked
                        if (obj != null) {
                            obj.addNewItem(ReceiveAmount);
                            listview.setAdapter(obj);
             Toast.makeText(getApplicationContext(),sum+"",Toast.LENGTH_SHORT).show();
                            addOrRemoveFooter(sum);
                        }
                    } 
                }
            }
        }

  public void addOrRemoveFooter(double sum2) {
    if (search.size() == 0 && listview.getFooterViewsCount() > 0) {
        listview.removeFooterView(footerLayout);
        Toast.makeText(getApplication(),"In"+sum2+"",Toast.LENGTH_SHORT).show();
    } else if (listview.getFooterViewsCount() == 0 && search.size() > 0) {
        Toast.makeText(getApplication(),"Out"+sum2+"",Toast.LENGTH_SHORT).show();
        listview.addFooterView(footerLayout);
        listview.setAdapter(obj);
        totalAmount.setText(sum2 + "");
    }
    else
    {
        Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_SHORT).show();
    }
}

The toast now display 15, but the setText always 5...Why ?

At first everything seems fine as it display Out in addOrRemoveFooter Toast.makeText(getApplication(),"Out"+sum2+"",Toast.LENGTH_SHORT).show();,but when I add the second time it display error.


Solution

  • In order to solve the add up problem, just change =+ to +=