Sergio
Sergio

Reputation: 529

Cannot make a static reference to the non-static method sendEmptyMessage(int) from the type Handler

I have an error "Cannot make a static reference to the non-static method sendEmptyMessage(int) from the type Handler"

How to fix it? As I think this is a problem that this class where I do this is not an activity?

        new Thread() {
            public void run() {
            try {

                    List<Sail> sails = searchSails();

                    selectSailIntent.putParcelableArrayListExtra(
                            Constant.SAILS, new ArrayList<Sail>(sails));

                    getContext().startActivity(selectSailIntent);

                    Handler.sendEmptyMessage(0);

                } catch (Exception e) {
                     alertDialog.setMessage(e.getMessage());
                     Handler.sendEmptyMessage(1);

                }
            }
        }.start();
    }
};

Upvotes: 2

Views: 6779

Answers (2)

SJuan76
SJuan76

Reputation: 24895

Handler handler = new Handler();
Handler.myStaticMethod();
handler.myNonStaticMethod();

In order to invoke a non-static method (aka instance methods) you must refer to a particular object (instance). You cannot refer to the class.

Static methods can be invoked by referencing only the class (they can also be called from a reference to an object of that class, but that is considered bad practice).

About usage: when you create an instance (object), that object has some inner data (state). Non static methods make use of the state of the object that is referenced, static methods do not need that data).

Upvotes: 3

aioobe
aioobe

Reputation: 421130

"Cannot make a static reference to the non-static method sendEmptyMessage(int) from the type Handler"

This is due to the fact that Handler refers to a class, but sendEmptyMessage is not a static method (should be called on an object, and not on a class).

How to fix it?

To be able to call the sendEmptyMessage method you will either

  1. Need to instantiate a Handler, i.e., do something like

    Handler h = new Handler();
    h.sendEmptyMessage(0);
    

    or

  2. Add the static modifier to the sendEmptyMessage method:

    public static void sendEmptyMessage(int i) { ...
           ^^^^^^
    

Upvotes: 9

Related Questions