mori mori - 2 years ago 311
Android Question

Error in remoteMessage.getNotification().getBody() [FCM]

I implemented Firebase Cloud Messaging in my application and while using the Firebase console my application in Android and iOS receives my notifications. But because I wanted to push notification daily I created a cron job to do that in my server side. I notice that every time i trigger my cron my application crashes

In my iOS client it doesn't receive any notification.

In my android client it displays an error:

java.lang.String$Notification.getBody()' on a null object reference

Where it is in my
here is my code

public class MyFirebaseMessagingService extends FirebaseMessagingService {

public void onMessageReceived(RemoteMessage remoteMessage) {

Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());


And in my server-side

function sendNotificationFCM($apiKey, $registrationIDs, $messageText,$id) {

$headers = array(
'Authorization:key=' . $apiKey

$message = array(
'registration_ids' => $registrationIDs,
'data' => array(
"message" => $messageText,
"id" => $id,

$ch = curl_init();

curl_setopt_array($ch, array(
CURLOPT_POSTFIELDS => json_encode($message)

$response = curl_exec($ch);

return $response;

I'm wondering why am I having a NPE and how can I solve it?

Answer Source

Try to add a notification object on your $message. The body of your POST request must be something like:

    "to" : "aUniqueKey",
    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark"
    "data" : {
      "Nick" : "Mario",
      "Room" : "PortugalVSDenmark"

Your remoteMessage.getNotification() returnsnull because the body of your POST request doesn't contain a notification object.

Use notifications when you want FCM to handle displaying a notification on your client app's behalf. Use data messages when you want your app to handle the display or process the messages on your Android client app, or if you want to send messages to iOS devices when there is a direct FCM connection.

Check the Documentation for Advanced Messaging Options for your reference.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download