Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

java - Android custom listener for an event

I'm trying to fire an event when an integer value is updated, but it's failing. Here's the code I'm using:

Declaring The Custom Listener

public class fieldactivity extends AppCompatActivity implements View.OnClickListener {
    OnModeUpdate modeupdate; //Create custom listener for mode update

    int mode = 1;

Mode Update Code

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fieldsignals);
        Button button = (Button) findViewById(R.id.mode_rotate_button);
        button.setOnClickListener(this);
    }

 @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case(R.id.rotate_button):
                mode += 1;
                modeupdate.onEvent(); //Fire Custom Lisentener - Fails On This Line
        }

    }

Interface Code

public interface OnModeUpdate {
//BreakPoint here, but is never reached
        void onEvent();
    }

    public void setModeupdate(OnModeUpdate eventListener) {
        modeupdate = eventListener;
    }

The error I am getting is:

java.lang.NullPointerException: Attempt to invoke interface method 'void alveare.com.plcsignalconverter.fieldactivity$OnModeUpdate.onEvent()' on a null object reference

Is there something I am missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The NullPointerException is caused by calling methods on a null referenced object, which means that it 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
      */
    }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...