Which Context should YOU use to show Toast message from Fragment?

efe budak
efe budak
Jul 10, 2017 · 1 min read

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 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 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 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.

efe budak

Written by

efe budak

Android Developer efebudak.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade