user6750923
user6750923

Reputation: 479

How to change the activity when the progress bar ends in Android?

I want to change the activity after the progress bar ends. Means progress Bar thread ends. I am adding the activity2 after the thread. But the activity2 starts as the application runs. Why is it so?

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

        progressBar = (ProgressBar) findViewById(R.id.progressBar1);
        new Thread(new Runnable() {
            public void run() {
                while (progressStatus < 100) {
                    progressStatus += 1;
                    handler.post(new Runnable() {
                        public void run() {
                            progressBar.setProgress(progressStatus);
                        }
                    });
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();


        Intent myIntent = new Intent(getApplicationContext(), activity2.class);
        myIntent.putExtra("key", "......"); //Optional parameters
        startActivity(myIntent);

Upvotes: 1

Views: 1494

Answers (2)

niksya
niksya

Reputation: 291

You have created a new thread which is responsible for progress bar while on main thread your new activity code is executed. You need to place start activity code within the same thread.

What you can do is :

new Thread(new Runnable() {
    public void run() {
        while (progressStatus <= 100) {
                progressStatus += 1;
                handler.post(new Runnable() {
                    public void run() {
                        progressBar.setProgress(progressStatus);
                    }
                });
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        Intent myIntent = new Intent(getApplicationContext(), activity2.class);
        myIntent.putExtra("key", "......"); //Optional parameters
        startActivity(myIntent);
    }
}).start();

Upvotes: 1

Someone
Someone

Reputation: 560

This is because you start the progress bar in a new thread while the start of the intent is in another thread. The thread starting the intent does not wait for the progress bar to be finished because they are asynchronous. You could solve this by starting the intent in the runnable after the while loop is done.

Upvotes: 0

Related Questions