asedra_le
asedra_le

Reputation: 3067

Thread in Android

I have an example like this:

package android.uiexample;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class BasicViewsExampleActivity  extends Activity 
{

private static int progress = 0;
private ProgressBar progressBar;
private int progressStatus = 0;
private Handler handler = new Handler();

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.basic_views);

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

    //---do some work in background thread---
    new Thread(new Runnable() 
    {
        public void run() 
        {
            //---do some work here---
            while (progressStatus < 10) 
            {
                progressStatus = doSomeWork();
            }



            //---hides the progress bar---
            handler.post(new Runnable() 
            {
                public void run() 
                {
                    progressBar.setVisibility(View.GONE);
                }
            });

        }    

        //---do some long lasting work here---
        private int doSomeWork() 
        {
            try {
                //---simulate doing some work---
                Thread.sleep(500);
            } catch (InterruptedException e) 
            {
                e.printStackTrace();
            }
            return ++progress;
        }

    }).start();
}

}

In this example, it use Handler to post a Runable to exc progressBar.setVisibility(View.GONE);. I don't know why i can't call progressBar.setVisibility(View.GONE); directly:

            //---do some work here---
            while (progressStatus < 10) 
            {
                progressStatus = doSomeWork();
            }



            //---hides the progress bar---
            progressBar.setVisibility(View.GONE);

Anybody can tell me why i can't?

Upvotes: 1

Views: 274

Answers (3)

seand
seand

Reputation: 5296

Take a look at the Handler class. It provides a simple way to enqueue Runnable callbacks to run on the UI event thread.

Upvotes: 1

jkhouw1
jkhouw1

Reputation: 7350

changing the progressBar visibility is a UI operation. All UI operations must be done on the UI thread.

Upvotes: 0

superfell
superfell

Reputation: 19040

The android UI framework (like pretty much every UI framework before it) only allows you to update the UI state from the main thread. You may want to look at AsyncTask which include the plumbing needed to route progress updates onto the main thread.

Upvotes: 1

Related Questions