Fr4nkWh1te Fr4nkWh1te - 2 months ago 20
Android Question

Android: getContext() in Fragment returns null only when leaving over the Back Button

i have a Fragment, which contains and ArrayList of Pending Notification Intents.

I build that list of reminders in onPause(), because i only want the to show up when the App is not running in the foreground.

Everything works fine if i leave the app over the HomeScreen Button, but if i leave over the Back Button, the Compiler tells me i try to call getSystemService() on a Null Reference.

Main Activitie's onPause:

@Override
protected void onPause() {
super.onPause();
tasksFragment.buildReminderList();
}


Here the method from the Fragment:

public void buildReminderList() {

mReminderList = new ArrayList<>();

if (mTaskList != null) {

for (int i = 0; i < mTaskList.size(); i++) {

if (mTaskList.get(i).hasReminder() && mTaskList.get(i).getMillisLeftToday() > 0) {

AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
intent = new Intent(getContext(), AlertReceiver.class);

intent.putExtra("title", mTaskList.get(i).getName());
intent.putExtra("ID", i);

alarmIntent = PendingIntent.getBroadcast(getContext(), i, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, mTaskList.get(i).getReminderHour());
calendar.set(Calendar.MINUTE, mTaskList.get(i).getReminderMinutes());

if (calendar.before(Calendar.getInstance())) {
calendar.add(Calendar.DATE, 1);
}

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 60 * 24, alarmIntent);

mReminderList.add(alarmIntent);
}
}
}
}

Answer Source

When pressing the back button, the fragment is no longer attached to the activity, so getContext() returns null.

You can check if your fragment is still added to the activity and then call your getSystemServicelike below

if (isAdded()) {
   getContext().getSystemService(Context.ALARM_SERVICE)
}