tags:

views:

2734

answers:

2

Hi, I am having an class which extends Activity and i am trying to create an object of that class in normal java class ,It is giving me an exception "Cant create handler inside thread that has not called looper.prepare" ,what i am doing wrong Thnx in advance.

+1  A: 

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.

Robert Harvey
+1  A: 

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.

Prashast