我想将LocalBroadcastManager设置为侦听文本文件和图像文件,并相应地更新适配器。这是我的代码:
// register the receiver to listen for incoming messages
LocalBroadcastManager.getInstance(getBaseContext())
.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//Receive text messages
Message message = new Message(intent.getStringExtra(ChatFragment.INTENT_EXTRA_MSG));
message.setDeviceName(intent.getStringExtra(ChatFragment.INTENT_EXTRA_NAME));
message.setDirection(Message.INCOMING_MESSAGE);
adapter.addMessage(message);
//Log.i(TAG, "onReceive: received message to adapter");
//Receive image files
com.bridgefy.sdk.client.Message fmessage = intent.getParcelableExtra(FileFragment.INTENT_EXTRA_MSG);
byte[] fileBytes = fmessage.getData();
BridgefyFile bridgefyFile = new BridgefyFile((String)fmessage.getContent().get("file"));
bridgefyFile.setData(fileBytes);
bridgefyFile.setDeviceName(intent.getStringExtra(FileFragment.INTENT_EXTRA_NAME));
bridgefyFile.setDirection(BridgefyFile.INCOMING_FILE);
adapter.addFile(bridgefyFile);
}
}, new IntentFilter(conversationId));
收到消息后,应用程序崩溃并显示错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'byte[] com.bridgefy.sdk.client.Message.getData()' on a null object reference
我怀疑原因是因为BroadcastManager也正在以相同的意图监听图像
答案 0 :(得分:0)
收听文本文件和图像文件并更新适配器 相应地
您可以为此使用Actions
private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case "Action1":
break;
case "Action2":
break;
}
}
};
然后,当您发送广播时,只需根据自己的意图设置操作
intent.setAction("Action1")