Search code examples
javaandroidrunnableandroid-handler

Unable to use Handler properly


I started learning Android Development. I was building a basic addition game, where user has to click on button which shows the addition of two number. There are four Textviews. First one give the time limit for each question to answer. Second gives the question for the user. Third one gives the current score of the user and the last one gives whether the chosen open is correct or incorrect. Everything is working except the First Button. Every time when the button is pressed the the counting takes very fast.

Screenshot

// When First button is pressed

public void onClickButton1(View view) {
        correctIncorrect.setVisibility(View.VISIBLE);
        if (Integer.parseInt(button1.getText().toString())==sum) {
            correctIncorrect.setText("Correct");
            correctUpdater();
        }
        else {
            correctIncorrect.setText("Incorrect");
            inCorrectUpdater();
        }

}

//Similar to all the buttons


//To Update the score

public void correctUpdater() {
        n++;
        yourScore++;
        score.setText(Integer.toString(yourScore) + "/" + Integer.toString(n));
        update();
}

public void inCorrectUpdater() {
    n++;
    score.setText(Integer.toString(yourScore) + "/" + Integer.toString(n));
    update();
}


// To update the timer

//=======================================================================//
    public void resetTimer() {
        timer.setText(Integer.toString(temp)+"s");
        if (temp == 0) {
            inCorrectUpdater();
            update();
        }
        else {
            timeUpdater();
        }

    }

    public void timeUpdater() {
        Handler timeHandler = new Handler();
        Runnable timeRunnable = new Runnable() {
            @Override
            public void run() {
                temp--;
                resetTimer();
            }
        };
        timeHandler.postDelayed(timeRunnable,1000);
    }
    //=================================================================//

// Updater function

public void update() {

        correctIncorrect.setVisibility(View.INVISIBLE);
        Random random = new Random();
        int a = random.nextInt(21);
        int b = random.nextInt(21);
        question.setText(Integer.toString(a) + " + " + Integer.toString(b));
        Log.i("info", "onCreate: a = " + a);
        Log.i("info", "onCreate: b = " + b);
        sum = a+b;
        Log.i("info", "onCreate: sum = " + sum);
        int whichButton = random.nextInt(4);
        Log.i("info", "onCreate: random button is " + whichButton);
        values.clear();
        for (int i = 0; i< 4; i++) {
            if (i == whichButton) {
                values.add(sum);
            }
            else {
                values.add(random.nextInt(50));
            }
            Log.i("info", "onCreate: value[" + i + "] = " + values.get(i));
        }
        button1.setText(Integer.toString(values.get(0)));
        button2.setText(Integer.toString(values.get(1)));
        button3.setText(Integer.toString(values.get(2)));
        button4.setText(Integer.toString(values.get(3)));
        temp = 10;
        resetTimer();
}

Am I using the Handler incorrectly? What can I do?


Solution

  • Am I using the Handler incorrectly? What can I do?

    A better way to do this is CountDownTimer, by using this you won't have to deal with Handler youself and you also have a provision to cancel a running CountDownTimer.

    Everything is working except the First Button

    Not really sure what can cause different behaviours on click of buttons with the same code in onClick(). But you can consider using the same onClickListener for all the 4 buttons, in this way :

    View.OnClickListener myListener = new View.OnClickListener() {
            @Override
            public void onClick(View button) {
                correctIncorrect.setVisibility(View.VISIBLE);
                if (Integer.parseInt(button.getText().toString())==sum) {
                    correctIncorrect.setText("Correct");
                    correctUpdater();
                }
                else {
                    correctIncorrect.setText("Incorrect");
                    inCorrectUpdater();
                }
            }
        };
    
    button1.setOnClickListener(myListener);
    button2.setOnClickListener(myListener);
    button3.setOnClickListener(myListener);
    button4.setOnClickListener(myListener);
    

    This will ensure that clicking any of the 4 buttons will have a same behavior (depending on the answer of course)

    In case you get confused with the onTick() method on CountDownTimer, you can use modified CountDownTimer which will ensure that the timer doesn't miss any ticks.