DarShan Pandya

Making Fragments Bulletproof for NPEs

If you are using Fragments in your App then I’m sure you might have experienced a situation where the getActivity() returned null & your App came down Crashing with an NPE!

I recently met some of this NPEs in my App & decided to fix them (Nothing can be Fixed Up Completely 😂).

So here was my Implementation,
this approach make your Fragments “kinda” NPEs Bulletproof coz there are very, very rare chances of getting an Activity instance Null.

In your Activity where you are holding the Fragments, do this –

//Create a Static Activity Level Variable
private static AppCompatActivity mActivity;

//then in your OnCreate(), initialize it!
mActivity = MainActivity.this;

Next we again initialize it in onResume() –

    protected void onResume()
    mActivity = MainActivity.this;

Now create a Static Public method in your MainActivity like below –

public static MainActivity getStaticActivity(){
        return mActivity;
            return null;

After doing this,
Create a Class Level private Activity or AppCompatActivity variable in your Fragment e.g.

private AppCompatActivity mActivity;

In your Fragment’s onViewCreated() & onResume() methods, Initialize this above declared variable as below –

mActivity = MainActivity.getStaticActivity();

You can use this variable mActivity whenever & wherever needed in your Fragment, it won’t be Null now…

Note: If you use Activity variable instead of AppCompatActivity then you have to put an Activity cast, only if you are returning an AppCompatActivity instance from the getStaticActivity()

Activity mActivity = (Activity) MainActivity.getStaticActivity();


Leave a Comment