0

I am developing an ATM android app and whenever the app opens it crashes. Here is my code:

public class MainActivity extends AppCompatActivity {
    TextView balanceText;
    EditText input;
    Button withdrawButton;
    int balance = 0;
    @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Create the random number
        Random number = new Random();
        int balance = number.nextInt(10000);
        //Initialize the variables
        balanceText = (TextView)findViewById(R.id.balanceText);
        input = (EditText)findViewById(R.id.input);
        withdrawButton = (Button)findViewById(R.id.withdrawButton);
        do {
            balanceText.setText(balance);
        } while (balance > 0);
    }
    public void withdraw(View view) {
        try {
            String text = input.getText().toString();
            int withdrawal = Integer.parseInt(text);
            balance = balance - withdrawal;
            if (withdrawal > balance) {
                balanceText.setText("Insufficient funds");
            }
        }
        catch (Exception e) {
            balanceText.setText("Something went wrong");
        }
    }
}

Note: I don't rum on an emulator so I don't know what exception or error I am getting.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
  • Please post your crash log, otherwise it's impossible to tell what's causing the issue. Thanks – Drew Szurko Feb 22 '17 at 22:03
  • If you are running on device, show us the logcat. See: [Unfortunately MyApp has stopped. How can I solve this?](http://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) – Morrison Chang Feb 22 '17 at 22:04
  • 1
    Your do while looks like it will block the main thread for ever... Not a good thing – Gavin Harris Feb 22 '17 at 22:04

1 Answers1

0
  1. I do not know for what the loop is for. Looks for me, as if runs forever, because balance will not change. The method onCreate should not take too long. I would remove the loop here and change the balanceText directly in withdraw with the new value.
  2. setText(int) will crash, if the number is no string resource id. You probably mean: balanceText.setText(String.valueOf(balance));

Your loop in onCreate:

do {
    balanceText.setText(balance);
} while (balance > 0);