Sam97305421562
Sam97305421562

Reputation: 3037

Creating an object of Android Activity class

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.

Upvotes: 2

Views: 11356

Answers (2)

Prashast
Prashast

Reputation: 5675

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.

Upvotes: 4

Robert Harvey
Robert Harvey

Reputation: 180788

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.

Upvotes: 1

Related Questions