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

拥有回忆 提交于 2019-12-12 18:13:46

问题


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();
    }
};

回答1:


"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) { ...
           ^^^^^^
    



回答2:


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).



来源:https://stackoverflow.com/questions/6550512/cannot-make-a-static-reference-to-the-non-static-method-sendemptymessageint-fr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!