Firebase remoteMessage getData正确的NullPointer处理

时间:2017-05-29 10:47:29

标签: android firebase firebase-cloud-messaging

我在处理来自remoteMessage的NullPointer异常时遇到了一些问题。

我试过做简单的检查:

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

if(data != null) {
        Log.d(TAG, remoteMessage.getData().get("lat"));
        Log.d(TAG, remoteMessage.getData().get("lng"));
    }

我也更努力了:

  if(remoteMessage.getData().get("lat") != null) {
        Log.d(TAG, remoteMessage.getData().get("lat"));
    }

但它总是与NullPointer崩溃:

05-29 10:22:33.112 21028-24256/com.coderspeak.smog_app E/AndroidRuntime: FATAL EXCEPTION: pool-12-thread-1
                                                                     Process: com.coderspeak.smog_app, PID: 21028
                                                                     java.lang.NullPointerException: println needs a message
                                                                         at android.util.Log.println_native(Native Method)
                                                                         at android.util.Log.d(Log.java:139)
                                                                         at com.coderspeak.smog_app.services.fcm.AppFirebaseMessagingService.onMessageReceived(AppFirebaseMessagingService.java:50)
                                                                         at com.google.firebase.messaging.FirebaseMessagingService.zzl(Unknown Source)
                                                                         at com.google.firebase.messaging.FirebaseMessagingService.zzJ(Unknown Source)
                                                                         at com.google.firebase.messaging.FirebaseMessagingService.handleIntent(Unknown Source)
                                                                         at com.google.firebase.iid.zzb$1.run(Unknown Source)
                                                                         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)

我该如何正确检查?

1 个答案:

答案 0 :(得分:0)

你试过这种方式吗?

if (remoteMessage != null &&
    remoteMessage.getData() != null) {
    String yourMessage = remoteMessage.getData().get("lat"));

    if (yourMessage != null) {
         Log.d(TAG, yourMessage);
    }
}