Error creating thread inside a Handler

Asked

Viewed 74 times

3

I need to delay 5 seconds in one of the parts of my application:

final Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // Encadeia trabalho serializado
        jobChain.append(new Job() {
            public void doJob(final OnChainItemListener itemListener) {
                // Obtém metadados do Artigo
                onlineArticle.get(idArticle, new HttpJsonObjectListener() {
                    public void onRequestCompleted(JSONObject object, Integer httpStatus, CharSequence msg) {
                        offlineArticle.save(object, new HttpJsonObjectListener() {
                            public void onRequestCompleted(JSONObject object, Integer httpStatus, CharSequence msg) {
                                Log.v(this.getClass().getName(), "Artigo salvo!");
                            }
                        }, null);

                        itemListener.onRequestCompleted(object, httpStatus, msg);
                    }
                }, defFail);
            }
        });

    }
};
new Handler().postDelayed(runnable, 5000);

I tried to implement, but it turns out that all this gets inside an Handler and it gives me the following error:

java.lang.Runtimeexception: Can’t create Handler Inside thread that has not called Looper.prepare()

I read about it, that I would have to run on the main thread, but I’m not getting it done.

  • Can you post your main thread code? That’s where the other thread was called, the main thread.

  • I believe you are calling methods that deal with interface within a thread that is not allowed to do so. Take a look at this response here from the O.R. link

1 answer

0


I decided to do the following:

private void createHandler() {
    Thread thread = new Thread() {
      public void run() {
           Looper.prepare();

           final Handler handler = new Handler();
           handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                   // Ação a ser atrasada
                    handler.removeCallbacks(this);
                    Looper.myLooper().quit();
               }
            }, 2000);

            Looper.loop();
        }
    };
    thread.start();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.