I am new to the android studio and I was building a calculator app, my problem is whenever I enter a number and then select an operator the number from the text view vanishes like if I want 2+4
and I press 2
and then +
, 2
vanishes from the text view and then when I press 4
, +
vanishes from the text view but the result is correct
Here is my java code...
buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (edt1 == null){
edt1.setText("");
}else {
mValueOne = Float.parseFloat(edt1.getText() + "");
mAddition = true;
edt1.setText(null);
}
}
});
buttonSub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mValueOne = Float.parseFloat(edt1.getText() + "");
mSubtract = true ;
edt1.setText(null);
}
});
buttonMul.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mValueOne = Float.parseFloat(edt1.getText() + "");
mMultiplication = true ;
edt1.setText(null);
}
});
buttonDivision.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mValueOne = Float.parseFloat(edt1.getText()+"");
mDivision = true ;
edt1.setText(null);
}
});
buttonEqual.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mValueTwo = Float.parseFloat(edt1.getText() + "");
if (mAddition == true){
edt1.setText(mValueOne + mValueTwo +"");
mAddition=false;
}
if (mSubtract == true){
edt1.setText(mValueOne - mValueTwo+"");
mSubtract=false;
}
if (mMultiplication == true){
edt1.setText(mValueOne * mValueTwo+"");
mMultiplication=false;
}
if (mDivision == true){
edt1.setText(mValueOne / mValueTwo+"");
mDivision=false;
}
}
});
buttonC.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
edt1.setText("");
}
});
button10.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
edt1.setText(edt1.getText()+".");
}
});
}
You are collecting the data correctly, but you keep setting your edt1 to null, and then when you hit + edt1 will always be null
May i ask why you are using the same editText field for doing this??
I would suggest using 2 edittext fields.
1 for first number 1 for second number
and then display the result in a textview?
You can achieve something like this with the code below
Then you can collect data from first_number and second_number and displaying the result in result.