Error in remoteMessage.getNotification (). GetBody ()

I have applied Firebase Cloud Messaging in my application and, using the Firebase console, my application in Android and iOS receives my notifications. But since I wanted to push the notification daily, I created a cron job to do this on my server side. I notice that every time I run my cron, my application crashes

In my iOS client, it does not receive any notifications.

An error message appears in my android client:

java.lang.String com.google.firebase.messaging.RemoteMessage$Notification.getBody()' on a null object reference

Where is it in my FirebaseMessagingServicehere 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 on 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 am wondering why I have NPE and how can I solve it?

+7
source share
4

$. POST :

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

remoteMessage.getNotification() null, POST .

, , FCM . , , Android, iOS, FCM.

.

+25
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;
    }
0

I ran into the same problem and found a solution through several experiments.

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

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});
  })

On the Android side:

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

NullPointerExceptionarises due to what you use getNotification().getBody()instead getData().get("score")when you use Data Payloadinstead Notification Payloadon the server side:

const message = {
    data: {score: '850', time: '2:45'},
    tokens: nTokenArray
}
0
source
if (remoteMessage.getNotification() != null) {
   sendNotification(remoteMessage.getNotification().getBody());
}
-2
source

All Articles