context parameter for custom adapter - getApplicationContext() fails but 'this' works

吃可爱长大的小学妹 提交于 2019-12-06 15:31:38

You should pass the context of your activity while creating an adapter object. Application context is different from the activity context and they should never be interchanged. Using application context gives you the entire context for the application which depends on how you have set up your Application subclass is set up. While it can still compile, it may produce results that you do not expect. The reason for your crash is because of what has gone into your Application subclass and is likely specific to your case.

Simply put, adapter objects should use the local Activity context as this is the one that it is bound to.

Adapters should never get the Application context during initialization. As the link codeMagic mentioned, you should always pass along the Activity to a class object if it directly relates to the life of the Activity...of which adapters do.

Now, it's certainly possible to give the ArrayAdapter an application context. It won't crash or throw an error. However what it will do is render your views differently then expected. Mainly because the application context lacks the theming you may or may not have supplied for your App and/or specifically for a given activity.

As to why the crash occurs? Somethings specifically wrong with your code. My guess, you are defining mcontext as an Activity so its crashing in the custom constructor...or It's defined as a Context but being used somewhere that as an Activity context which is causing the crash.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!