首页 > 解决方案 > 单击通知时应用程序崩溃

问题描述

我创建了一个包含聊天功能的应用程序,当用户发送消息时,它会向接收者显示通知。

现在,我喜欢当用户收到通知并单击它时,它将打开具有所有功能的活动。

我发出的通知如下所示:

public void notifyThis(String title, String message, String uniqueID, String var1, String var2, String var3) {

        Intent intent = new Intent(this, ChatActivity.class);

        intent.putExtra("ChatID",var1);
        intent.putExtra("ReceiverID",var2);
        intent.putExtra("SenderID",var3);

        int RandomID = (int) System.currentTimeMillis();

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        NotificationCompat.Builder groupBuilder = new NotificationCompat.Builder(this,"191919")
                .setSmallIcon(R.drawable.ic_launcher_custom_background)
                .setGroup(uniqueID)
                .setGroupSummary(true);

        NotificationCompat.Builder messageBuilder = new NotificationCompat.Builder(this, "191919")
                .setSmallIcon(R.drawable.ic_launcher_custom_background)
                .setContentTitle(title)
                .setContentText(message)
                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setGroup( uniqueID )
                .setAutoCancel( true );

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.notify(uniqueID,0, groupBuilder.build());
        notificationManager.notify(RandomID, messageBuilder.build());

    }

到目前为止一切正常,当我调试时,我看到它var1, var2, var3不为空并且存在。

我的问题是,当我点击通知时,应用程序崩溃了,因为它说:

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

但是我不明白为什么如果通知的意图是在其中发送带有值的并且如果我这样阅读它,为什么它会让 SenderID 为空;

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );

        setContentView( R.layout.activity_chat );

        getSupportActionBar().hide();

        auth = FirebaseAuth.getInstance();

        chatID = getIntent().getExtras().getString( "ChatID" );

        receiverID = getIntent().getExtras().getString( "ReceiverID" );
        SenderID = getIntent().getExtras().getString("SenderID");

        if (SenderID.equals( auth.getUid() )) { HERE I GET THE ERROR SAYING SenderID IS NULL
            NotMyID = receiverID;
        } else {
            NotMyID = SenderID;
        }
    }

我读错了吗?据我了解,我在我的通知意图中发送了 SenderID,然后我getExtras从那个意图中发送它应该可以工作。

谢谢

标签: javaandroidfirebase-cloud-messagingandroid-notificationsandroid-pendingintent

解决方案


只需对 notifyThis 函数进行一些更改:

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

推荐阅读