I know, this is again a repeated question but my case it is different question.
I have a class abc with a static function & a Handler. Earlier i couldn’t able call handler from a static function. Then i googled for Access a non-static function from a static function & found an solution is to create an instance of class & access non-static variable. But now, why, i m getting this error.
E/AndroidRuntime(13343): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
public class abc
{
static public void Instantiate()
{
abc xyz = new abc();
xyz.handler.sendEmptyMessage(1); **//GETTING ERROR IN THIS LINE**
}
public Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
switch (msg.what)
{
}
}
}
}
My Question: How can i send message to handler from a static function?
Thankx.
check the place where you are doing this:
and replace it with
I hope you’re calling it from an Activity
Some Explanation (quoting bicska88) 🙂
What causes the problem, doesn’t have anything to do with the fact that you send a message to a
Handlerobject from within a static function. The problem is that you send a message to the handler from a thread that has not calledLooper.prepare()(as the error message says, the thread doesn’t have amessage loop). This may be fixed by explicitly callingLooper.prepare()before-while, or by running the code on the UIThread.