Reputation: 1
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()
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();
}
}
}
}
}
Upvotes: 0
Views: 86
Reputation: 3486
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
}
});
};
Upvotes: 1
Reputation: 2169
You should run progress bar only on Main Looper. Add
handler = new Handler(context.getMainLooper()) {
.....
}
Should work.
Upvotes: 0