简体   繁体   中英

Android intent via notification not keeping extra data

I'm trying to pass a String via an intent stored in a notification. But when I get the String out of the intent in the new fragment, it's a null and it gives me a NullPointerException.

Code to create notification (in method A of fragment A in activity A)

Notification.Builder mBuilder = new Notification.Builder(getActivity().getBaseContext());
        mBuilder.setContentTitle("My first notification");
        mBuilder.setContentText("Click to see the details...");
        mBuilder.setSmallIcon(R.drawable.ic_launcher);

        //Intent maken voor notification
        Intent intentVoorNotificatie = new Intent(getActivity(), activity_detail_notification.class);
        EditText edTekst = (EditText) getActivity().findViewById(R.id.etTekst);


        String strTekstNotificatie = edTekst.getText().toString();
        intentVoorNotificatie.putExtra("detailNotificatie", strTekstNotificatie);


        //Intent naar PendingIntent converteren
        PendingIntent pIntentVootNotificatie = PendingIntent.getActivity(getActivity().getBaseContext(),
                                                0, intentVoorNotificatie, PendingIntent.FLAG_ONE_SHOT);
        mBuilder.setContentIntent(pIntentVootNotificatie);

        //Notificatie tonen
        NotificationManager mNotificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1,mBuilder.build());

Method A of fragment B in activity B

//Haal doorgegeven tekst uit intent
    Intent intent = getActivity().getIntent();
    String strTekst = intent.getStringExtra("detailNotificatie");

    TextView tvTekst = (TextView) getActivity().findViewById(R.id.tvDetailVanNotificatie);
    tvTekst.setText(strTekst);

I get the nullPointer on the setText() method due to the String being empty when extracting it from the intent.

Did I do something wrong for data to get lost or dismissed?

Try to change this code `

 PendingIntent pIntentVootNotificatie = PendingIntent.getActivity(getActivity().getBaseContext(),
                                                0, intentVoorNotificatie, PendingIntent.FLAG_ONE_SHOT);

to this `

PendingIntent pIntentVootNotificatie = PendingIntent.getActivity(getActivity().getBaseContext(),
                                                0, intentVoorNotificatie, PendingIntent.FLAG_UPDATE_CURRENT);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM