Home » Android » android – Error in remoteMessage.getNotification().getBody()

android – Error in remoteMessage.getNotification().getBody()

Posted by: admin June 15, 2020 Leave a comment

Questions:

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 com.google.firebase.messaging.RemoteMessage$Notification.getBody()' on a null object reference

Where it is in my FirebaseMessagingService here is my code

public class MyFirebaseMessagingService  extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

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

    sendNotification(remoteMessage.getNotification().getBody());
} 

And in my server-side

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


$headers = array(
    'Content-Type:application/json',
    'Authorization:key=' . $apiKey
);

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


$ch = curl_init();

curl_setopt_array($ch, array(
    CURLOPT_URL => 'https://fcm.googleapis.com/fcm/send',
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POSTFIELDS => json_encode($message)
));

$response = curl_exec($ch);
curl_close($ch);

return $response;
}

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

How to&Answers:

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.

Answer:

if (remoteMessage.getNotification() != null) {
   sendNotification(remoteMessage.getNotification().getBody());
}

Answer:

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



    $headers = array(
        'Content-Type:application/json',
        'Authorization:key=' . $apiKey
    );

    $message = array(
        'registration_ids' => $registrationIDs,
        'data' => array(
                "message" => $messageText,
                "id" => $id,
        ),
     'notification' => array(
                "body" => "body of notification",
                "title" => "title for notification",
        )
    );


    $ch = curl_init();

    curl_setopt_array($ch, array(
        CURLOPT_URL => 'https://fcm.googleapis.com/fcm/send',
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => json_encode($message)
    ));

    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
    }

Answer:

I faced the same issue and found out the solution through few experiments.

I am using Node backend where my Sample Push (Taken from Google Firebase) looks like:

const message = {
    data: {score: '850', time: '2:45'},
    tokens: nTokenArray
}


admin.messaging().sendMulticast(message)
  .then((response) => {
    if (response.failureCount > 0) {
      const failedTokens = [];
      response.responses.forEach((resp, idx) => {
        if (!resp.success) {
          console.log('resperrorresperrorresperrorresperror', resp.error);
          failedTokens.push(registrationTokens[idx]);
        }
      });
      console.log('List of tokens that caused failures: ' + failedTokens);
    }
  })
  .catch(fcmError => {
    console.log({'FCM Errors': fcmError});
  })

At Android Side:

Log.d(TAG, "BodyScore: " + remoteMessage.getData().get("score"));

NullPointerException is due to when you use getNotification().getBody() instead of getData().get("score") when you are using Data Payload instead of Notification Payload at server side:

const message = {
    data: {score: '850', time: '2:45'},
    tokens: nTokenArray
}