0

How to automatically Click a Button in Android after a 5 second delay

I tried with the codes that are entered in the link but my application has crashed My codes;

 public class MainActivity extends AppCompatActivity {
    Button button;
    TextView text;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            buttonClick();
            Thread timer = new Thread() {
                public void run() {
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        button.performClick();

                    }
                }
            };
            timer.start();
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                button.performClick();
            }
        }, 1000);

    }

    public void buttonClick() {
        button=(Button) findViewById(R.id.button);
        text=(TextView) findViewById(R.id.text);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Random s=new Random();
                int number=s.nextInt(3);
                switch (number)
                {case 1:text.setText("1");
                    break;
                    case 2: text.setText("2");
                        break;


                }
            }
        });

    }

}

Logcat Error

Community
  • 1
  • 1
Grkwnxs
  • 9
  • 1
  • 2

2 Answers2

0

You need to use

runOnUiThread(new Runnable() {
    @Override
    public void run() {
}
});

to avoid this error.

Please check Android "Only the original thread that created a view hierarchy can touch its views."

Also you can just use the Handler to perform the button click after a specified amount of time, no need to use the timer.

Community
  • 1
  • 1
0

This is more simpler method to run every second. you dont need to trigger the button. just call the method you want to execute

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

        Handler handler = new Handler();

        Runnable runnable = new Runnable(){
            @Override
            public void run() {
                buttonClick();
                if(handler!=null)
                    handler.postDelayed(runnable, 1000);
            }
        }

        handler.postDelayed(runnable, 1000);

    }
ZeroOne
  • 8,996
  • 4
  • 27
  • 45