'I want to be able to change activies either automatically or by pressing button. This code works, but it bugs out after pressing a button

How could I fix this? It works but it bugs out. I don't know what to try any more. I want activity to change either by button press or automatically. And if button isn't pressed to continue on the next activity- not to skip some of them.

public class Ljeto extends AppCompatActivity {

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

This is the start, i have defined intent and buttons.

        Button button = findViewById(R.id.NaprijedLjeto);
        Button button1 = findViewById(R.id.NazadLjeto);
        Intent intent = new Intent(this, MainActivity.class);
        Intent intent1 = new Intent(this, Proljece.class);
        Intent intent2 = new Intent(this, MainActivity.class);
        Timer timer = new Timer();

Here i started the actions which work perfect. All up until timer.

       button.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               startActivity(intent);
           }
       });

       button1.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
              startActivity(intent1);
           }
       });

       timer.schedule(new TimerTask() {
           @Override
           public void run() {
               startActivity(intent2);
           }
       }, 5000);
   }
}

This work is for my school. I have tried everything I know but it just doesn't work for some reason.



Solution 1:[1]

*Use this code

 new  Handler().postDelayed(() -> {
        startActivity(intent2);

    },5000);

instead of

    timer.schedule(new TimerTask() {
        @Override
        public void run() {




            startActivity(intent2);



        }
    }, 5000);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Manjeet deswal