1

In my android app I have a service and an activity that binds to that service. In order to update the views in the activity I use interfaces as suggested in this answer. I preferred interfaces over broadcast receivers since the code is cleaner, also I feel broadcast receivers are slow and a little unpredictable. However that is a different issue. The problem I face is that in my activity class I initiate the callback like this

private ServiceConnection serviceConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        // cast the IBinder and get MyService instance
        LocalBinder binder = (LocalBinder) service;
        myService = binder.getService();
        bound = true;
        myService.setCallbacks(MyActivity.this); // register
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        bound = false;
    }

This line does it

    myService.setCallbacks(MyActivity.this); // register

Then in my service I call methods implemented in my activity like this.

myService.callActivityMethod()

Problem is that sometimes I get a null pointer exception in my service when I call the method on this callback.

java.lang.NullPointerException: Attempt to invoke interface method 'void com.my.app.services.myService.callActivityMethod()' on a null object reference

This means that the callback which I initiate inside onServiceConnected is null. I can't think of a situation when this might happen. It works fine mostly but I have got few crash reports that show this error. Can someone please help me figure why this might be happening and what might be a way to prevent this from happening. Thanks !!

Community
  • 1
  • 1
varunkr
  • 5,364
  • 11
  • 50
  • 99

0 Answers0