Makk
Makk

Reputation: 5

handler.postDelayed not running every second

The problem/question is that these lines of code arent repeating.

   handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Counter+= ButtonCounter(Counter);
            Counter+= AutoCounter(Counter, add);
            Display(Counter, myTextView);
        }
    },1000);  

I want the code to repeat every second, but it only repeats once a second after the program starts. Is the postdelayed only supposed to run once.If so, which method would i use to run everysecond instead of just once.

package com.example.navjeevenmann.mytycoon;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
private Button myButton;
private int Counter = 0;
private Button myButton2;
private TextView myTextView;
Handler handler = new Handler();
private int add = 0;
private int timer = 1000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myButton = (Button) findViewById(R.id.button);
    myButton2 = (Button) findViewById(R.id.button2);
    myTextView = (TextView) findViewById(R.id.textView);
    myButton.setOnClickListener(new View.OnClickListener() {
        @Override

        public void onClick(View view) {
        }
    });
    myButton2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
            intent.putExtra("Count", Counter);
            startActivity(intent);
            finish();
        }

    });

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Counter+= ButtonCounter(Counter);
            Counter+= AutoCounter(Counter, add);
            Display(Counter, myTextView);
        }
    },1000);    }

public int ButtonCounter(int Counter) {
    Counter += 1;
    return Counter;
}

public int AutoCounter(int Counter, int add) {
    Counter += add;
    return Counter;
}

public void Display(int Counter, TextView myTextView) {
    String man = String.valueOf(Counter);
    myTextView.setText("$" + man);
}






}

Upvotes: 0

Views: 807

Answers (1)

huk
huk

Reputation: 220

try to put handler.postDelayed(this, 1000) after Display(Counter, myTextView) like this:

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        Counter+= ButtonCounter(Counter);
        Counter+= AutoCounter(Counter, add);
        Display(Counter, myTextView);
        handler.postDelayed(this, 1000);
    }
},1000);    }

Upvotes: 3

Related Questions