Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i send message to handler from a static function?

Tags:

android

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.

like image 225
MicroEyes Avatar asked Jul 14 '12 11:07

MicroEyes


2 Answers

check the place where you are doing this:

abc.Instantiate();

and replace it with

runOnUiThread(new Runnable() {

    @Override
    public void run() {
        abc.Instantiate();
    }
});

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 Handler object from within a static function. The problem is that you send a message to the handler from a thread that has not called Looper.prepare() (as the error message says, the thread doesn't have a message loop). This may be fixed by explicitly calling Looper.prepare() before-while, or by running the code on the UIThread.


like image 186
Sherif elKhatib Avatar answered Nov 14 '22 21:11

Sherif elKhatib


try defining the handler as

final static Handler handler = new Handler() { ... };
like image 37
mihail Avatar answered Nov 14 '22 22:11

mihail