Search code examples
androidbroadcastreceiverandroid-notifications

Object return null when putExtra and getSerializable on BroadcastReceiver


I just want to pop the Title to the notification but this is return null object. I need help pls, my English is very bad I hope everyone will sympathy :D.

Error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.a.Work.getTitle()' on a null object reference at com.example.a.AlertBrr.onReceive(AlertBrr.java:24)

CreateActivity.class

            Work work = new Work();
            work.setTitle(ctitle.getText().toString());
            work.setDate(edittext.getText().toString());
            work.setContent(ccontent.getText().toString());
            Database database = new Database(CreateActivity.this);
            database.add(work);
            //
            Intent intent = new Intent(CreateActivity.this, AlertBrr.class);
            intent.putExtra("work", work);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(CreateActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, myCalendar.getTimeInMillis(), pendingIntent);

AlertBrr.class:

public class AlertBrr extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Work work = (Work) intent.getSerializableExtra("work");

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "duong")
                .setContentTitle(work.getTitle())
                .setContentText(work.getContent())
                .setContentInfo(work.getDate())
                .setSmallIcon(R.drawable.done);

        NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
        managerCompat.notify(100, builder.build());
    }
}


Solution

  • Ha Minh, I've taken a look at your project. Thanks for sharing it, that helped a lot!

    To fix this issue you have to wrap the Work object into a Bundle and then pass the Bundle into the Intnet. Your code in CreateActivity#onOptionsItemSelected should look like this:

    Intent intent = new Intent(CreateActivity.this, AlertBrr.class);
    Bundle bundle = new Bundle();
    bundle.putSerializable("work", work);
    intent.putExtra("work_bundle", bundle);
    

    And in AlertBrr#onReceive:

    Bundle workBundle = intent.getParcelableExtra("work_bundle");
    Work work = (Work) workBundle.getSerializable("work");
    

    Note: I got the idea of this stackoverflow answer.