Question

My activity_main.xml contains this progressBar, which starts hidden ("gone")

<ProgressBar
       android:id="@+id/progressBar_sendingPhoneNumber"
       style="?android:attr/progressBarStyleLarge"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_below="@id/button_sendPhoneNumber"
       android:layout_centerInParent="true"
       android:visibility="gone" />

And my MainActivity.java has this,
An onClick handler for a button I have

    final Context context = this;

    sendPhoneNumberButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar_sendingPhoneNumber);
            progressBar.setVisibility(View.VISIBLE);

            // Simulate HTTP connection
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            progressBar.setVisibility(View.GONE);

            // Redirect to new activity
            Intent intent = new Intent(context, InboxActivity.class);
            startActivity(intent);
        }
    });

The problem is that the progress bar is never shown, although the onClick code is executed (eg. it is redirected to the new activity at the end). So the line:

progressBar.setVisibility(View.VISIBLE);

Isn't taking effect.

I think this has to do with the context, and trying to change the visibility of the progressBar from "outside" the activity, but i'm not sure.

How can I solve this?

Was it helpful?

Solution

It is never shown because you are calling

try {
    Thread.sleep(3000);
 } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

that makes "sleep" the thread responsible to draw the same ProgressBar you are trying to show

OTHER TIPS

Calling Thread.sleep(3000); on the UI thread will block the UI thread. You should not block the UI thread.

http://developer.android.com/training/articles/perf-anr.html

If you implement Thread or HandlerThread, be sure that your UI thread does not block while waiting for the worker thread to complete—do not call Thread.wait() or Thread.sleep()

Also, you can move this:

ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar_sendingPhoneNumber);

outside View.onClick. No need to initialize the view every time you click your Button.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top