Home » Android » android – NullPointerException when using LocalBroadcastManager

android – NullPointerException when using LocalBroadcastManager

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to use LocalBroadcastManager with my custom intents.
It seems that it’s very picky about intents and If I send the intent this way:

In Myintents.java I declare

public static final String LOCATION_UPDATE = "com.example.myapp.location_update";

Later on in the broadcast sender I do:

Intent intent = new Intent(MyIntents.LOCATION_UPDATE);
localBroadcastManager.sendBroadcast(intent);

Then I’m getting this exception:

05-05 02:23:29.914: E/AndroidRuntime(6952): FATAL EXCEPTION: main 
05-05 02:23:29.914: E/AndroidRuntime(6952): java.lang.NullPointerException 
05-05 02:23:29.914: E/AndroidRuntime(6952): at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:297) 
05-05 02:23:29.914: E/AndroidRuntime(6952): at android.support.v4.content.LocalBroadcastManager.access$000(LocalBroadcastManager.java:46)  
05-05 02:23:29.914: E/AndroidRuntime(6952): at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:116) 
05-05 02:23:29.914: E/AndroidRuntime(6952): at android.os.Handler.dispatchMessage(Handler.java:99)

However If I use an explicit string

Intent intent = new Intent("my-intent");

Everything works fine.

What’s wrong? Why can’t I define the intent name in another class?

How to&Answers:

I just came across this. The NPE is a result of the registered listener (read: receiver) for the event you are firing (MyIntents.LOCATION_UPDATE) not having been instantiated by the component hosting it.

Check that the thing you want to respond to this broadcast has actually been instantiated at the right point (probably the hosting activity/fragment).

Answer:

In my case, (I had the same error) I forgot to create an instance of my class that extends the BroadcastReceiver. (and overrides the onReceive() method)

    private MeasurementUpdateReceiver   m_MeasurementUpdateReceiver;

// Listens to local broadcasts done by the MeasurementService
private class MeasurementUpdateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Intent already filtered by the LocalBroadcastManager in onResume()
        String data = intent.getStringExtra("data"));
        Toast.makeText(getApplicationContext(), "Received data " + data, Toast.LENGTH_LONG).show();
    }
}

Passing an empty reference of this class to the LocalBroadcastManager with:

LocalBroadcastManager.getInstance(this).registerReceiver(m_MeasurementUpdateReceiver, new IntentFilter("measurementupdate"));

wasn’t a problem until it tries to invoke the onReceive() method of the class. What I forgot was:

m_MeasurementUpdateReceiver = new MeasurementUpdateReceiver();

I hope this helps other people facing this error.