0

I keep getting "Application not responding" when trying to implement a CountDownTimer. Here's what I have:

private TextView mTextField;
private EditText secText;
private int secs;
private Button buttonStart, buttonStop;

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

    mTextField = (TextView) findViewById(R.id.textView1);
    secText = (EditText) findViewById(R.id.segText);
    buttonStart = (Button) findViewById(R.id.buttonStart);
    buttonStop = (Button) findViewById(R.id.buttonStop);
    secs = Integer.parseInt(secText.getText().toString());

    final CountDownTimer count = new CountDownTimer((secs*1000), 1000) {
         public void onTick(long millisUntilFinished) {
             mTextField.setText("Seconds remaining: " + millisUntilFinished / 1000);
         }
         public void onFinish() {
             mTextField.setText("FINISHED!");
         }
      };

The problem is with this line when it tries to parse, if I put a number it works:

secs = Integer.parseInt(secText.getText().toString());
Gorby Oz
  • 83
  • 9
  • an edit text is awaiting a user input...what You do is that You directly parse an integer from Your editText which is not there....or have You set this number as a default value inside xml? – Opiatefuchs Nov 20 '14 at 14:50
  • @Opiatefuchs I get your point. I tried with a number inside the xml and it works. Now I'll like to do it with the number that the user puts. – Gorby Oz Nov 20 '14 at 15:07

2 Answers2

0

You need to handle all the cases when trying to get the text from the EditText.

  1. What if the EditText is empty?
  2. What if the value in the EditText is not an Integer? ("1bs25", or "hello")

You need to consider these things and handle them properly before trying to parse the value into an Integer and start the timer.

AnxGotta
  • 1,006
  • 7
  • 28
  • I used this: `android:inputType="number"` to avoid string values. – Gorby Oz Nov 20 '14 at 15:04
  • Yes. The point still stands that you aren't properly handling all possible cases when pulling the Editable from the EditText. I see stealthjong worded the same response a bit differently and you understand now. All good =) – AnxGotta Nov 20 '14 at 15:21
0

Make sure you know the sequence of actions you need to perform. Here's some pseudo code

if buttonstart_clicked
    get text from sectext
    if text is empty
        show error
    else if text is notANumber
        show error
    else
        parse text AND start timer

You forgot your starting point is the button click, not the start of the application, because your edittext is still empty by then.

stealthjong
  • 10,858
  • 13
  • 45
  • 84