I'm trying to obtain a value input from the user called spent, from what I was able to understand the value is stored in the variable spent but then I am not able to use it for the calculations.

public float spent, spentperson, totalspent, totaldivision,  debt;
public short people;

TextView debtoutput;
EditText spentinput;
Button Addbtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bills);

    debtoutput = findViewById(R.id.debtoutput);
    spentinput = findViewById(R.id.spentinput);
    Addbtn = findViewById(R.id.addbtn);

    Addbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            spent = Float.valueOf(spentinput.getText().toString());

            //showToast(String.valueOf(spent));
        }
    });


    showToast(String.valueOf(spent));

    people = 4;            //temporary
    spentperson = 5;        //temporary
    totalspent = spent + totalspent;
    totaldivision = totalspent / people;
    debt = totaldivision - spentperson;

    showToast(String.valueOf(debt));

    if (spent != 0) {
        if (debt < 0) {
            debtoutput.setText("You owe the following amount: " + debt);
        } else if (debt > 0) {
            debtoutput.setText("Someone is owing you: " + debt);
        } else {
            debtoutput.setText("There is no debt");
        }
    }
}

1 Answers

0
Community On

I didn't test yet, but at first look, you're retrieving the value from the EditText inside the onClick, so, the rest of the code doesn't have access to this value.

You could, maybe, put all of this inside a method like this:

public void yourMethod(String spent){

  //convert spent
  double spentValue = Double.parseDouble(spent);

  people = 4;            //temporary
  spentperson = 5;        //temporary
  totalspent = spentValue + totalspent;
  totaldivision = totalspent / people;
  debt = totaldivision - spentperson;

  if (spentValue != 0) {
      if (debt < 0) {
          debtoutput.setText("You owe the following amount: " + debt);
      } else if (debt > 0) {
          debtoutput.setText("Someone is owing you: " + debt);
      } else {
          debtoutput.setText("There is no debt");
      }
  }
}

//And you call it in the onClick method like this:


  Addbtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          yourMethod(spentinput.getText().toString());
      }
  });



//I don't know your main goal with this code, although, you can use the same logic for other code snippets.

//Hope it can help you. Have a nice day!