Why is RemoteMessage.getData() returning null in firebase notifications?

Viewed 3141

I'm using the notification composer in firebase to send the following key value pair using Custom data:

 type : 555

I'm not putting double-quotes "" around type and 555 in the notification composer. So in the place for key I'm writing type and in the place for value I'm writing 555 . Following is my code to retrieve this value of type :

@Override
    public void onMessageReceived(final RemoteMessage remoteMessage) {


        final Map<String, String> data = remoteMessage.getData();
        final String type = data.get("type");
        Log.e("TAG","Type= "+type);

}

But the log output I'm getting is:

Type= null

Why am I getting null? How do I correctly retrieve the value of the given key?

EDIT It appears that

final Map<String, String> data = remoteMessage.getData();

works all right. I put a Log.e() statement after this line and it correctly prints 555. So it appears that data.get("type") is returning null even though the key "type" is present. Why is this happening?

1 Answers

I was facing same problem. After some search, I came up with the solution below.

@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    
    RemoteMessage.Notification data = remoteMessage.getNotification();
    String title = data.getTitle();
    String body = data.getBody();
    
    if (data != null){
        // do some work
    }
    
}

I tried and it worked for me. I hope it will help others.

Related