2

I have a class which extends Activity and I am trying to create an object of that class in a normal java class but it's throwing me an exception :

Can't create handler inside thread that has not called looper.prepare

What am I doing wrong?

Thanks in advance.

1
  • how on earth do you expect anyone to help you, when you can't be bothered posting a detailed question? Aug 1, 2009 at 5:06

2 Answers 2

4

You should read up on the application fundamentals of android apps

I cannot think of an example where you would need to create an activity object yourself. you should be using the Context.startActivity() call to start an activity.

Anyways, to answer your question - an activity implements a message queue (using a Handler) where messages can be sent to the activity's running thread to perform certain tasks. That means the thread which executes Activity code stays around waiting for these messages (an example of these messages are the users' response to your applications UI). In order to do that you need to use a Looper thread which "loops" (or in a way waits) for messages to act on. The main thread for your application which also renders the UI for your application is a looper thread.

If for some reason you are having the need to create an activity object manually then you should rethink how you are designing your application. Using startActivity is all that is required.

1

The handler runs in whatever thread created it. So if you're not creating the instance of the new class in the UI thread then the handler isn't running in the UI thread and you will have a problem.

I once tried to inflate GUIs in a separate thread for performance reasons. I didn't touch any Window at that point, but when inflating I got the same error message and I just ran Looper.prepare() in my Thread and all was well.

A Looper runs the message loop of a thread. If you don't call Looper.prepare() (and then Looper.loop()) in a thread, that thread won't have a message loop, so can't have Handler objects that accept messages.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.