My app cashes when i click submit, it doesnt verify the fields as it should.
It works the way i want to but if i click on submit without entering anything it crashes.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addBtn = (Button) findViewById(R.id.addBtn);
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText amoutGiven = (EditText) findViewById(R.id.amountG);
EditText manyPeople = (EditText) findViewById(R.id.mPeople);
EditText moenyGiven = (EditText) findViewById(R.id.moneyG);
TextView changeTxt = (TextView) findViewById(R.id.changeTxt);
Button nxtBtn = (Button) findViewById(R.id.nxtBtn);
Button tryBtn = (Button) findViewById(R.id.tryBtn);
android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
if (amoutGiven.getText().length()==0){
amoutGiven.setError("This field is required");
}
if (manyPeople.getText().length()==0){
manyPeople.setError("This field is required");
}
if (moenyGiven.getText().length()==0){
moenyGiven.setError("This field is required");
}
int num1 = Integer.parseInt(amoutGiven.getText().toString());
int num2 = Integer.parseInt(manyPeople.getText().toString());
int num3 = Integer.parseInt(moenyGiven.getText().toString());
int total = num1 * num2;
int change = num3 - total;
changeTxt.setVisibility((changeTxt.getVisibility() == View.VISIBLE)
? View.INVISIBLE : View.VISIBLE);
if (change < 0 ){
changeTxt.setText("Your numbers dont add up");
tryBtn.setVisibility((tryBtn.getVisibility() == View.VISIBLE)
? View.INVISIBLE : View.VISIBLE);
tryBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, MainActivity.class));
}
});
}else {
changeTxt.setText( "Give Back Change oF: R" + change +"" );
nxtBtn.setVisibility((nxtBtn.getVisibility() == View.VISIBLE)
? View.INVISIBLE : View.VISIBLE);
nxtBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, MainActivity.class));
}
});
}
}
});
}
}