it says that looper.prepare must be called

I am updating progress bar with the help of handler of MainActivity but it gives the error :Can't create handler inside thread that has not called Looper.prepare()

Error

public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
Handler handler;
Thread thread;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    thread = new Thread(new MyThread());
    thread.start();
    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            progressBar.setProgress(msg.arg1);
        }
    };


}

class MyThread implements Runnable {

    @Override
    public void run() {
        Message message = Message.obtain();

        for (int i = 0; i < 100; i++) {
            message.arg1 = i;
            handler.sendMessage(message);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

}

2 answers

  • answered 2017-06-17 18:49 A. Shevchuk

    You should run progress bar only on Main Looper. Add

        handler = new Handler(context.getMainLooper()) {
    .....
    }
    

    Should work.

  • answered 2017-06-17 18:49 Sanoop

    The error is because you are updating your UI from a different thread. So what you should be doing is like call the update method on main ui thread

    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
              runOnUiThread(new Runnable() {
                   @Override
                   public void run() {
                       // Do something on UiThread
                       // update progress
                   }
              });
     };