使用LocalBroadcastManager时出现空指针异常

11

我正在尝试使用LocalBroadcastManager与我的定制意图。

看起来它对意图非常挑剔,如果我以这种方式发送意图:

在Myintents.java中,我声明

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

稍后在广播发送器中,我执行以下操作:

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

然后我收到了这个异常:

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)

然而,如果我使用显式字符串

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

一切都运行良好。

出了什么问题?为什么我不能在另一个类中定义意图名称?


1
公共静态最终字符串 "LOCATION_UPDATE =(引号前的 LOCATION_UPDATE),那是一个打字错误吗?" - Sudhee
"LocalBroadcastManager.java:297" 的内容是什么? - k3b
不是打错了,LocalBroadcastManager 是 Android 框架的一部分,不是我的。 - ApriOri
有进展了吗@ApriOri - 我也奇怪地开始看到它了... - BrantApps
2个回答

17

我刚刚看到这个。NPE是由于你正在触发的事件(MyIntents.LOCATION_UPDATE)的已注册监听器(即接收器)尚未被包含它的组件实例化引起的。

请检查您想要响应此广播的内容是否已在正确的位置(可能是承载活动/碎片)实例化。


那么你如何解释显式字符串问题?我不明白为什么将内联字符串更改为静态最终字符串变量会有任何区别。 - ApriOri
我怀疑这是因为意图[action] (http://developer.android.com/reference/android/content/Intent.html#Intent(java.lang.String))已经从另一个接收器在其意图过滤器中注册的某个东西(即在广播该操作时被调用)更改为任意内容(“my-intent”而不是“com.example.myapp.location_update”)。 LocalBroadcastManager没有找到任何已注册接收“my-intent”操作的监听器,因此没有发生任何事情。 - BrantApps
你可以在AOSP中看到这个链接 - BrantApps
在创建我的类实例之前,我正在注册接收器。 - Ankit
我忘记在onCreate中初始化接收器实例。谢谢,这很有用。 - yeeen

12
在我的情况下(我遇到了同样的错误),我忘记创建一个实例,该实例扩展了BroadcastReceiver类,并覆盖了onReceive()方法。
    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();
    }
}

将这个类的空引用传递给LocalBroadcastManager:
LocalBroadcastManager.getInstance(this).registerReceiver(m_MeasurementUpdateReceiver, new IntentFilter("measurementupdate"));

这不是问题,直到它试图调用类的onReceive()方法。我忘记了:

m_MeasurementUpdateReceiver = new MeasurementUpdateReceiver();

我希望这篇文章能够帮助其他遇到这个错误的人。


我在onCreate(Fragment的)中创建了接收器,并在onAttach中注册了接收器。出现了这个错误,所以请确保您在同一位置创建接收器。 - Gober

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接