-1

I'm using Firebase cloud messaging and one of the parameters is optional. I have following method below

public void onMessageReceived(RemoteMessage remoteMessage) {
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        String picUrl = null;

        String toTel = remoteMessage.getData().get("To").toString();
        if (remoteMessage.getData().get("Pic") != null)
            picUrl = remoteMessage.getData().get("Pic").toString();
}

However I'm getting an exception at the if statement line

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference

How can I successfully check to is there is a value for "Pic"?

david
  • 997
  • 3
  • 14
  • 34
  • 1
    maybe the problem is `remoteMessage.getData().get("To").toString()`, or maybe it should only be called once – Scary Wombat Mar 29 '18 at 00:29
  • no, it works fine without the if statement, and the exception does show the line number of the if statement – david Mar 29 '18 at 00:30
  • *works fine without the if statement* - please edit your question to show what you mean – Scary Wombat Mar 29 '18 at 00:32
  • *works fine wihtout the if statement* - post the stack trace and tell us which line threw the exception. – user207421 Mar 29 '18 at 00:57
  • I do not believe this code throws this exception. I suspect the real code was `if (remoteMessage.getData().get("Pic").toString() != null)`. Note the `.toString()` call. – user207421 Mar 30 '18 at 04:13

1 Answers1

2

I tend to use containsKey method rather than checking for null, maybe try this

if (remoteMessage.getData().containsKey("Pic")) {
    picUrl = data.get("Pic");
}
mononz
  • 1,665
  • 1
  • 12
  • 17