codepath / android_guides

Extensive Open-Source Guides for Android Developers
guides.codepath.com
MIT License
28.31k stars 6.35k forks source link

Will context.getApplicationContext return null happen? #356

Open aiueoH opened 5 years ago

aiueoH commented 5 years ago

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.

kamiljeglikowski commented 5 years ago

Can you show those crashes?

pablichjenkov commented 5 years ago

Possible in theory bizarre in practicality.

nareshkatta99 commented 5 years ago

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.

aiueoH commented 5 years ago

Can you show those crashes?

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

aeramli commented 5 years ago

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

aemxn commented 5 years ago

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