When I send a notification message with data payload on foreground, my application crashes. It works fine when it is in background or killed state but why it doesn't work on foreground?
This is the error:
java.lang.NullPointerException at ... MyFirebaseMessagingService.onMessageReceived(MyFirebaseMessagingService.java:57)
and the error indicates the line given in MyFirebaseMessagingService:
if(dataType.equals(getString(R.string.direct_message))){
Compiler already catches the problem and it says:
Method invocation 'equals' may produce 'java.lang.NullPointerException'
This is a small part of Firebase Messaging Service class:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private static final int BROADCAST_NOTIFICATION_ID = 1;
@Override
public void onDeletedMessages() {
super.onDeletedMessages();
}
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String notificationBody = "";
String notificationTitle = "";
String notificationData = "";
try{
notificationData = remoteMessage.getData().toString();
notificationTitle = remoteMessage.getNotification().getTitle();
notificationBody = remoteMessage.getNotification().getBody();
}catch (NullPointerException e){
Log.e(TAG, "onMessageReceived: NullPointerException: " + e.getMessage() );
}
Log.d(TAG, "onMessageReceived: data: " + notificationData);
Log.d(TAG, "onMessageReceived: notification body: " + notificationBody);
Log.d(TAG, "onMessageReceived: notification title: " + notificationTitle);
String dataType = remoteMessage.getData().get(getString(R.string.data_type));
if(dataType.equals(getString(R.string.direct_message))){
Log.d(TAG, "onMessageReceived: new incoming message.");
String title = remoteMessage.getData().get(getString(R.string.data_title));
String message = remoteMessage.getData().get(getString(R.string.data_message));
String messageId = remoteMessage.getData().get(getString(R.string.data_message_id));
sendMessageNotification(title, message, messageId);
}
}
}
I guess (getString(R.string.direct_message)
is null but I don't know why it is null on foreground. How can I solve the problem?