Pourquoi l'appel à getActivity() peut parfois retourner null ? Et du coups générer un java.lang.NullPointerException pour les éléments qui l'utilisent....

getActivity() returns null in Fragment function

// This happened when you call getActivity() in another thread that finished after the fragment has been removed. 
// The typical case is calling getActivity() (ex. for a Toast) when an HTTP request finished (in onResponse for example).
// To avoid this, you can define a field name mActivity and use it instead of getActivity(). 
// This field can be initialized in onAttach() method of Fragment as following:

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
    mActivity = activity;
}

et ses critiques sur Android. Fragment getActivity() sometime returns null

  • I have a bad feeling about that, keeping reference to an activity is not a good practice
  • Don't call methods within the Fragment that require getActivity() until onStart in the parent Activity.
@Override
	public void onAttach(Activity activity) {

	@Override
	public void onDetach() {

You should use the Application context available in the Fragment Activity

getActivity().getApplicationContext();

You shouldn't use the getActivity() as context here because Toast can live longer than the activity that showed it (Home button as been pressed, another activity has been launched, etc.)

you need a Context with the lifecycle separated from you Activity's Context to know if you need to use getActivity().getApplicationContext() or just getActivity().

Fragments

What is Context in Android? You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in the activity class).

java.lang.Object

  ↳	android.content.Context
	   ↳	android.content.ContextWrapper
	 	   ↳	android.view.ContextThemeWrapper
	 	 	   ↳	android.app.Activity

java.lang.Object

  ↳ 	android.content.Context
 	   ↳ 	android.content.ContextWrapper
 	  	   ↳ 	android.app.Application
// Compiled from Activity.java (version 1.5 : 49.0, super bit)
public class android.app.Activity extends android.view.ContextThemeWrapper implements android.view.LayoutInflater$Factory2, android.view.Window$Callback, android.view.KeyEvent$Callback, android.view.View$OnCreateContextMenuListener, android.content.ComponentCallbacks2 {

// Compiled from ContextThemeWrapper.java (version 1.5 : 49.0, super bit)
public class android.view.ContextThemeWrapper extends android.content.ContextWrapper {
  
// Compiled from ContextWrapper.java (version 1.5 : 49.0, super bit)
public class android.content.ContextWrapper extends android.content.Context {

// Compiled from Context.java (version 1.5 : 49.0, super bit)
public abstract class android.content.Context {