vcmkrtchyan
vcmkrtchyan

Reputation: 2626

How to make setContentView() work properly with a thread?

I have 2 layouts, and 2 activities, each one corresponding to a layout, one of them is SplashActivity, and the other is MainActivity. I want the application to open the splashActivity(splash XML shows the logo), wait for 5 seconds and open the main activity, but because of the thread, the setContentView doesn't work properly.

P.S. Also any relative documentation links would be very useful, thanks in advance

@Override

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash_screen);

    Thread timer = new Thread() {
        public void run() {
            try {
                sleep(5000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }

            try {
                Class mainMenu = Class.forName("com.carmine.project.MenuActivity");
                Intent openMainMenu = new Intent(SplashActivity.this, mainMenu);
                startActivity(openMainMenu);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    };

    timer.run();
}

Upvotes: 2

Views: 323

Answers (1)

Blackbelt
Blackbelt

Reputation: 157437

your problem is that you are calling timer.run(); instead of timer.start();

timer.run(); calls the run method on the same context of the thread that executed that line (making the UI Thread, in your case, wait for 5s, and blocking every other operation). timer.start() spawns a new thread

Upvotes: 3

Related Questions