简体   繁体   中英

While loop doesn't work on Android

I need to display numbers with a delay of 1 second. Without the while loop it works but once I add the while loop it prints the value after the while loop ends. Can someone help in this regard.

int state = 0;
int count=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button=(Button)findViewById(R.id.b_main);
    textView =(TextView) findViewById(R.id.text_main);
    listView =(ListView) findViewById(R.id.t_main);
    arrayList=new ArrayList<String>();

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(state==0){
                state=1;
                try {
                    while(count<10) {
                        textView.setText("Start " + count++);
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else{
                state=0;
                textView.setText("Stop " + count++);
            }
        }
    });
}

Never call Thread.sleep() on the UI thread. You need to put the code in a separate thread, and post the result using runOnUiThread :

if(state==0){
    state=1;

    new Thread(new Runnable() {
        @Override
        public void run() {

            try {
                while(count<10) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textView.setText("Start " + count++);
                        }
                    });

                    Thread.sleep(1000);
                    count++;
                } 
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
        }
    }).start();
}

Don't use Thread.sleep() . Use a handler to enforce the delay you want.

    final Handler handler = new Handler();
    final int delay1 = 1000; // adjust as needed


     handler.postDelayed(new Runnable() {
                public void run() {

                    // Code Block 1. Code here will be executed after 1000 millisec


                }
            }, delay1);


//  Code Block 2. Code here will be executed immediatelly ( before **Code Block 1** )

As you are doing operation related to time the better approach would be to use CountDownTimer . It is bad to use Thread.sleep() on main thread because your Ui will get stuck when thread is sleeping

Here is an example on how to achieve it CountDownTimer

int state = 0, count = 0;
    TextView textView;
    CountDownTimer timer;


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

        button=(Button)findViewById(R.id.b_main);
        textView =(TextView) findViewById(R.id.text_main);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (state == 0) {
                    state = 1;

                    startTimer();

                } else {
                    state = 0;
                    if (timer != null) {
                        timer.cancel();
                    }
                    textView.setText("Stop " + count++);
                }
            }
        });
    }

    public void startTimer() {
        timer = new CountDownTimer(10000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                    count++;
                    textView.setText("Start " + count);
            }

            @Override
            public void onFinish() {
                       //10 sec finished
            }
        };

        timer.start();

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM