Android custom listener for an event

旧城冷巷雨未停 提交于 2019-11-29 12:37:04

The NullPointerException is caused by calling methods on a null referenc object, which is an object that has not been initialized.

In your case, the null object is modeUpdate. Try to initialize it in the onCreate() of your activity.

modeupdate = new OnModeUpdate() {
    @Override
    public void onEvent() {
      /**
      * Write the code to handle the case
      */
    }
};

More general name for listener is observer * design pattern. Speaking the pattern terminology what you're trying to achieve is to make an observer, i.e modeupdate, get notified when an event (integer value change) occurrs within an observable object, i.e.fieldactivity interacting with a user.

The observer, modeupdate, may be of any type and must implement the OnModeUpdate interface in order to receive notifications from the observable object. E.g.**

public class CustomListener implements OnModeUpdate {
    @Override
    public void onEvent() {
        ...
    }
}

Now you can assign the observer (modeupdate) within the observable object (fieldactivity) by one of the following options (according to your business logic):

  • initialize modeupdate with an "external" class instance

    OnModeUpdate modeupdate = new CustomListener();
    
  • initialize modeupdate with an anonymous inner class instance within fieldactivity class

    modeupdate = new OnModeUpdate() {
        @Override
        public void onEvent() {
            // Do stuff regarding the mode change
        }
    };
    
  • assign modeupdate from outside of the fieldactivity class by calling setModeupdate(...) on the reference to fieldactivity instance ***.

Above said explains the cause of NullPointerException. You never initialized modeupdate. After the initialization of modeupdate the onEvent() method will be triggered on a button click.

Note: you wrote in the comment to your code: "... BreakPoint here, but is never reached." It cannot be reached within the interface declaration, only on an instance of the object that implements the interface.


* Another name of the pattern is Subscriber-Publisher pattern.
** If OnModeUpdate interface is declared within fieldactivity use public class CustomListener implements fieldactivity.OnModeUpdate
*** Same as you did with the button variable by calling setOnClickListener() outside of the Button class and assigning a listener, i.e. an object (fieldactivity) that implements View.OnClickListener interface

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