Reputation: 267
I'm starting to study threads and I don't understand why the following simple code does not work. It is throwing:
RuntimeException: can't create handler inside thread that has not called looper.prepare():
Here's the code
public void onClick(View v) {
switch (v.getId()) {
case R.id.id1:
Thread th =new Thread(new Runnable() {
public void run() {
update();
delObjects();
addObjects();
}
});
th.start();
break;
}
}
I have read that sometimes the error occurs when you try to modify the UI, but it's not my case.
Thanks in advance!
Upvotes: 0
Views: 58
Reputation: 16558
If you are not accessing the UI stuff, then the chances are you are doing deep threading. Basically you cannot start a thread from unside a run() method which is already threaded. So your methods,
update();
delObjects();
addObjects();
might be using threading and which causes this issue. In most cases, you don't need such threading since you are already outside the UI thread and so you can skip to have threading inside these functions. In some cases if these functions has to be used somewhere else where no wrapper thread is running, you might need to have threads in the methods itself. So if that is the case, change your code as the following.
public void onClick(View v) {
switch (v.getId()) {
case R.id.id1:
Thread th = new Thread(new Runnable() {
public void run() {
//Prepare for further threading.
Looper.prepare();
update();
delObjects();
addObjects();
}
});
th.start();
break;
}
}
Hope that helps.
Upvotes: 1
Reputation: 9889
When you create the thread, you use var name "th", but when you start the thread, you use "th1". Is this a typo when you ask question, or it's error in your code?
Upvotes: 0