Philipp Meissner
Philipp Meissner

Reputation: 5482

Update ProgressBar within MainThread in AndroidAPP

I have 2 buttons as well as a progressbar. Now I want to count from 0 - 100 and update the progressbar with the counter. Unfortunately this count is so fast, that I will not see a progress (I can only see the progressbar jump from 0 to 100 within a 'millisecond'.).

This is what I tried so far, however the same thing happens as before.

I click the button to start the counter, the app becomes unresponsive (I calculate within the mainThread, so that is OKAY (and exactly what I want to accomplish here(!))) and shortly after sets the progressbar to 100. Nothing in between.

Now if you could head me into the correct direction, that'd be highly appreciated! :)

public class MainActivity extends ActionBarActivity {
    public String TAG = "MainActivity";

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

        addButtonListeners();
    }

    public void addButtonListeners() {
        Button firstButton, secondButton;
        final ProgressBar pgBar;

        firstButton = (Button) findViewById(R.id.first_button);
        secondButton = (Button) findViewById(R.id.second_button);
        pgBar = (ProgressBar) findViewById(R.id.progressBar);


        firstButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "First Button was pressed.");
                for (int i = 0; i <= 100; i++) {
                    countProgBarUp(pgBar, i);
                }
            }
        });

        secondButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "Second Button was pressed.");

            }
        });

    }

    public void countProgBarUp(ProgressBar pgBar, int counter) {
        try {
            Thread.sleep(100);
            pgBar.setProgress(counter);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
...
}

Upvotes: 0

Views: 380

Answers (1)

Larry Schiefer
Larry Schiefer

Reputation: 15775

The UI becomes unresponsive because you are doing this on the main thread and sleeping. If you do not return from the onClick() then the main thread cannot handle UI changes, such as displaying your new progress. Only the main thread can update UI components and draw them. It is often called the UI thread because of this.

You could try creating a Runnable which updates the progress bar to the new count. Create a Handler which is bound to the UI thread and call postDelayed() for the Handler and give it an instance of the Runnable. Then in the Runnable just post it again as long as you haven't reached you max progress.

Upvotes: 1

Related Questions