Search code examples
androidservicenullpointerexceptionandroid-broadcastreceiver

Broadcast Receiver null pointer Android


I keep getting the following error:

> java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.BroadcastReceiver.onReceive(android.content.Context, android.content.Intent)' on a null object reference

When I try to receive a broadcast from my service class.

Service:

   @Override
public void onDestroy(){
    super.onDestroy();
    Intent intent = new Intent("UpdateLocation");
    intent.putExtra("Location",journ);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

That is the code to send the broadcast sending a custom object(Journ) to my main activity.

Main:

  @Override
protected void onCreate(Bundle savedInstanceState) 

  LocalBroadcastManager.getInstance(this).registerReceiver(
            mReceiver, new IntentFilter("UpdateLocation"));

    //Listen for service to send location data
    mReceiver = new BroadcastReceiver() {
        @Override
       public void onReceive(Context context, Intent intent) {
            temp= intent.getExtras().getParcelable("Location");
        }
    };
}

   @Override
    public void onPause() {
        if (!tracking) {
            finish();
        }
        //Run service in background to keep track of location
   startService(new Intent(this, locationService.class));
        super.onPause();
    }

    @Override
    public void onResume() {
        if (!tracking) {
            return;
        }
        if (mGoogleApiClient != null) {
            //Reconnect to google maps
            mGoogleApiClient.reconnect();
        }
       stopService(new Intent(this, locationService.class));
        super.onResume();
    }

I am not sure how to go about doing this, I am trying to pass the object from my service class which runs when my app is in the background and when it resumes the service should stop and sends the data it gathered to my main activity.

This, however, doesn't work, any ideas?

In case people were wondering my on create method does contain more code, but I didn't think it necessary to include.


Solution

  • In onCreate mReciever is a null object (if you didn't assign it earlier), so you should assign it before registering a receiver. Change this part:

    if (mReceiver == null) {
        mReceiver = new BroadcastReceiver() {
             @Override
             public void onReceive(Context context, Intent intent) {
                 temp= intent.getExtras().getParcelable("Location");
            }
        };
    }
    
    //Listen for service to send location data
    LocalBroadcastManager.getInstance(this)
        .registerReceiver(mReceiver, new IntentFilter("UpdateLocation"));