Guy Balas
Guy Balas

Reputation: 96

Android Timer doesn't work well

private int count = 0;
private float totalmoney = 0, constant=(1/3);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView) findViewById(R.id.textView);
    buttonStart = (Button) findViewById(R.id.start);
    textView.setText("minutes= " + count + " money= " + totalmoney);
    buttonStart.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Timer T = new Timer();
            T.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            count++;
                            totalmoney = totalmoney+constant;
                            textView.setText("minutes= " + count + " money= " + totalmoney);
                        }
                    });
                }
            }, 60000, 60000);

        }
    });
}

Hello all, I want to have a timer, running every minute, starting from 0 and every minute add (1/3) to the totalmoney float, My code is above, it is working very well, the minutes count is also working good but the totalmoney is permanently zero. I tried at first using totalmoney += (1/3) but it didn't work so I changed my code a bit with a constant of (1/3), why does it stay zero?

Upvotes: 0

Views: 188

Answers (1)

Anindya Dutta
Anindya Dutta

Reputation: 1982

float constant = 1/3

Here 1/3 is first divided as integers, hence 1/3 = 0. Then it is converted to float (becomes 0.00...). Effectively, you are always adding 0 to your totalmoney.

Update the constant to (float)1/3 or 1f/3 and the code should be working fine.

Upvotes: 1

Related Questions