Joseph
Joseph

Reputation: 21

How to add all values from edit text and displaying the total value on another Activity listview

The tutorial was from Droid Guru https://www.youtube.com/watch?v=DETCfQ_EOXo

  1. I wanted to get the sum of all numbers in edit text through iteration and display it on another activity.

'''

private boolean checkIfValidAndRead() {
    budgetInfos.clear();
    boolean result = true;

    for (int i = 0; i < layoutList.getChildCount(); i++) {

        View itemView = layoutList.getChildAt( i );
        EditText editItemName = (EditText) itemView.findViewById( R.id.budget_edittext_item );
        EditText editPrice = (EditText) itemView.findViewById( R.id.budget_edittext_price );
        
        BudgetInfo budgetInfo = new BudgetInfo();

        if (!editItemName.getText().toString().equals( "" )) {
            budgetInfo.setItem( editItemName.getText().toString() );
        } else {
            result = false;
            break;
        }
        if (!editPrice.getText().toString().equals( "" )) {
            budgetInfo.setItem( editPrice.getText().toString() );
        } else {
            result = false;
            break;
        }

        budgetInfos.add( budgetInfo );

        
    }
    if (budgetInfos.size() == 0) {
        result = false;
        Toast.makeText( this, "Add an item first.", Toast.LENGTH_SHORT ).show();
    } else if (!result) {
        Toast.makeText( this, "Enter all blank fields correctly.", Toast.LENGTH_SHORT ).show();
    }
    return result;
}

enter image description here

Thank you Sai H!!! I used the given code to my second activity from the comment.

//Passed the values through intent from main activity to second activity
budgetInfos = (ArrayList<BudgetInfo>) getIntent().getExtras().getSerializable( "list" );

        int total = 0;
        for (BudgetInfo price : budgetInfos) {
            total += price.getPrice();
            textView.setText( "Total Budget: " + total );}
  
`

Upvotes: 1

Views: 113

Answers (2)

Rahul Rai
Rahul Rai

Reputation: 596

Just store the value in a variable and pass the variable to the next activity using intent extra.

            Intent i = new Intent(MainActivity.this, NextActivity.class);
            i.putExtra("total", budgetInfo);
            startActivity(i);

And access the value from the next activity as :

 int total = getIntent().getIntExtra("total");

Upvotes: 1

Sai H.
Sai H.

Reputation: 66

From the look of it, I don't think you need to get int values from EditTexts because all your values are in budgetInfo instances. If you just create an ArrayList<budgetInfo>, you can loop through the ArrayList to find the sum and add the result in your Intent to start another Activity.

Upvotes: 2

Related Questions