android_guides icon indicating copy to clipboard operation
android_guides copied to clipboard

Will context.getApplicationContext return null happen?

Open aiueoH opened this issue 6 years ago • 6 comments

According to this page Understanding the Android Application Class

The application object is not guaranteed to stay in memory forever

So the application will be released when somes components is alive? My app has some crash reports caused by application null pointer exception in service.

aiueoH avatar Jan 26 '19 00:01 aiueoH

Can you show those crashes?

kamiljeglikowski avatar Jan 26 '19 00:01 kamiljeglikowski

Possible in theory bizarre in practicality.

pablichjenkov avatar Jan 26 '19 01:01 pablichjenkov

Yes it will some times. We faced the same issue. You should use context.getApplicatinContext when it requires to place some thing global level. You can use them for things like toast etc but not for creating UI etc.

nareshkatta99 avatar Jan 27 '19 06:01 nareshkatta99

Can you show those crashes?

It happened on a few devices. I can't reproduce.

aiueoH avatar Jan 28 '19 06:01 aiueoH

Services are running in a different sandbox from the app, having a service running doesn't guarantee keeping the app alive. You might have to change your approach of "setting things globally" -> Broadcast, sharedpreferences ...Etc

aeramli avatar Jan 28 '19 08:01 aeramli

Careful when using getApplicationContext as it would cause memory leak when using it with long living object. Try some other contexts as described here

aemxn avatar Jan 28 '19 18:01 aemxn