-1

I tried reading the Android documentation but there doesn't seem to be any information on how to handle cases where getApplicationContext() returns null.

Should i do a check with a

try{
    mContext = application.getApplicationContext()
} catch (NullPointerException e) 

}

or should i do a null check

if(application.getApplicationContext() == null)
{
 return;
}

Does getApplicationContext throw any Exception or Fatal Exception? Or just returns null?

Mysterious_android
  • 598
  • 2
  • 9
  • 32
  • 1
    Just returns null – Northern Poet Oct 13 '17 at 00:53
  • wait, @EJP, why delete your answer? It was good for discussion. I tested his code `activity.getApplicationContext` did throw a NPE – Mysterious_android Oct 13 '17 at 01:26
  • That will only throw an NPE if activity is null. getApplicationContext itself will never return null on a properly initialized context. – Gabe Sechan Oct 13 '17 at 01:41
  • @nicko_yuan I have neither deleted nor even provided an answer. The deleted answer was 100% incorrect in all respects. The only way that line of code can throw an NPE is if `activity` itself is null, which it wasn't in his contrived example, which therefore did not throw the exception he showed. I have no idea how you managed it, but it wasn't with his code. – user207421 Oct 13 '17 at 01:58
  • *Does* it return null? I can't see any evidence in the Javadoc that it *either* returns null *or* throws an exception of any kind. – user207421 Oct 13 '17 at 02:44

1 Answers1

0

I tried reading the Android documentation but there doesn't seem to be any information on how to handle cases where getApplicationContext() returns null.

There is nothing in the documentation to suggest that it ever returns null.

Should i do a check with a

try{
    mContext = application.getApplicationContext()
} catch (NullPointerException e) 

}

No, why? The only way that can ever catch anything is if application is null, according to the Javadoc.

or should i do a null check

if(application.getApplicationContext() == null)
{
 return;
}

I don't see why. There is nothing to suggest that it ever returns null.

Does getApplicationContext throw any Exception or Fatal Exception? Or just returns null?

According to the Javadoc, neither. Of course if the Javadoc is wrong it's anybody's guess, but I can't see how the application context can ever be null in a running activity.

user207421
  • 305,947
  • 44
  • 307
  • 483