简体   繁体   中英

Getting a RuntimeException from within some sample threading code

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!

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.

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?

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