Skip to content
Advertisement

App crashes when receiving notification from firebase PHP API

I want to send a notification to a user via firebase PHP API. I followed a tutorial but the app crashes when the API runs and if the app it’s not open nothing will happen.

this is the code:

<?php

define( 'API_ACCESS_KEY', 'Server_key' ); // get API access key from Google/Firebase API's Console

$registrationIds = array( 'fUAIyAPjSSGfiykT6Y0PwC:APA91bGxIDUfgD01tfNjyd12NxMsPq_Dv_O72ifh6fYL-_6P_WLanGJCjyxKo7JkF2QyyJjIsF__HKePJACI7bMl9NEkeXN1uyUhiu1-DkISpworIoVNpzT4gXLy0w92dtEF94mD5T8G' ); //Replace this with your device token


// Modify custom payload here
$msg = array
(
        'mesgTitle'     => 'SMART TESTING',
        'alert'         => 'This is sample notification'

);
$fields = array
(
    'registration_ids'      => $registrationIds,
    'data'                  => $msg
);

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

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' ); //For firebase, use https://fcm.googleapis.com/fcm/send

curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;

?>

I can send notifications via firebase without any problem. NOTE: I’m running PHP code on localhost with Xampp.

here’s my app code:

MainActivity

protected void onCreate(Bundle savedInstanceState) {
        checkFirstRun=Boolean.FALSE;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        prefs = getSharedPreferences("com.example.fonefinder", MODE_PRIVATE);






        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationChannel notificationChannel=
                new NotificationChannel(MyNotification.CHANNEL_ID,MyNotification.CHANNEL_NAME,NotificationManager.IMPORTANCE_HIGH);
        notificationChannel.setDescription(MyNotification.CHANNEL_DESCRIPTION);
        //notificationChannel.enableLights(true);
        //notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationManager.createNotificationChannel(notificationChannel);
        

    }

FirebaseInstanceIdService:

public class FirebaseInstance extends FirebaseInstanceIdService {
    public String refreshedToken;
    @Override

    public void onTokenRefresh() {
        // Get updated InstanceID token.
        refreshedToken = FirebaseInstanceId.getInstance().getToken();
        //Log.d("MyToken",refreshedToken);

FirebaseMessagingService:

public class FirebaseMessaging extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        String title=remoteMessage.getNotification().getTitle();

        String body=remoteMessage.getNotification().getBody();
        MyNotification.getInstance(getApplicationContext()).displayNotification(title,body);


    }

}

MyNotification:

public class MyNotification {
    public static final String CHANNEL_ID="myChannelID";
    public static final String CHANNEL_NAME="myChannelName";
    public static final String CHANNEL_DESCRIPTION="myChannelDescription";
    private Context nCtx;
    private static MyNotification myNotification;
    private MyNotification(Context context){
        nCtx = context;
    }
    public static synchronized MyNotification getInstance(Context context){
        if (myNotification==null){
            myNotification = new MyNotification(context);
        }
        return myNotification;

    }
    public void displayNotification(String title,String body){
        NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(nCtx,CHANNEL_ID)
                .setSmallIcon(R.drawable.icon)
                .setContentText(title)
                .setContentTitle(body);
        Intent intent = new Intent(nCtx,MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(nCtx,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
        nBuilder.setContentIntent(pendingIntent);
        NotificationManager notificationManager = (NotificationManager) nCtx.getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager!=null){
            notificationManager.notify(1,nBuilder.build());
        }
    }
}

Error:

2020-12-20 17:17:32.602 19407-19484/com.example.fonefinder E/AndroidRuntime: FATAL EXCEPTION: Firebase-Messaging-Intent-Handle
    Process: com.example.fonefinder, PID: 19407
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.messaging.RemoteMessage$Notification.getTitle()' on a null object reference
        at com.example.fonefinder.FirebaseMessaging.onMessageReceived(FirebaseMessaging.java:9)
        at com.google.firebase.messaging.FirebaseMessagingService.dispatchMessage(com.google.firebase:firebase-messaging@@21.0.0:64)
        at com.google.firebase.messaging.FirebaseMessagingService.passMessageIntentToSdk(com.google.firebase:firebase-messaging@@21.0.0:34)
        at com.google.firebase.messaging.FirebaseMessagingService.handleMessageIntent(com.google.firebase:firebase-messaging@@21.0.0:27)
        at com.google.firebase.messaging.FirebaseMessagingService.handleIntent(com.google.firebase:firebase-messaging@@21.0.0:17)
        at com.google.firebase.messaging.EnhancedIntentService.lambda$processIntent$0$EnhancedIntentService(com.google.firebase:firebase-messaging@@21.0.0:43)
        at com.google.firebase.messaging.EnhancedIntentService$$Lambda$0.run(Unknown Source:6)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
        at com.google.android.gms.common.util.concurrent.zza.run(Unknown Source:6)
        at java.lang.Thread.run(Thread.java:784)

Advertisement

Answer

i found the problem:

public class FirebaseMessaging extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        String title=remoteMessage.getNotification().getTitle();

        String body=remoteMessage.getNotification().getBody();
        MyNotification.getInstance(getApplicationContext()).displayNotification(title,body);


    }

}

firebase API doesn’t support remoteMessage so if you remove it and set title and body manually problem will be solved.

I don’t know how to get the title and body from API.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement