Which Context should YOU use to show Toast message from Fragment?
If your fragment is not attached to an activity you will get an Null Pointer Exception (NPE) while trying this code;
Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
Right Answer
“ApplicationContext” is the right answer!
HOW?
So, the new question is; how can I get the application context in my fragment? My lazy, and effective, answer to this is; you @Inject it by the help of the awesome library called Dagger 2. (Here is a good dagger.android tutorial)
Here is an example;
Wrong approach
Another answer to getting the ApplicationContext from the fragment is;
Toast.makeText(getContext().getApplicationContext(), message, Toast.LENGTH_LONG).show();
However, your getContext() method will return null, so it is pointless.
If you have another good solution to this problem I would love to hear it. Leave a comment about that. ;)
Here is the whole sample project;
Edit: A good solution without using dagger is keeping the application context static.
public class MyApplication extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
MyApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MyApplication.context;
}
}
Here is the original stackoverflow link.