问题
I have simple code snippet to implement custom list view.
In this code, I have CustomAdapter
class which extends ArrayAdapter
:
CustomAdapter adapter = new CustomerAdapter(getApplicationContext(),R.layout.listview_item_row, weather_data);
The constructor of CustomAdapter
is as below:
public CustomerAdapter(Context context, int layoutResourceId, weather[] data) {
super(context, layoutResourceId, data);
mlayoutResourceId = layoutResourceId;
mcontext = context;
mdata = data;
}
If I write this, the logcat shows following error:
Java.lang.ClassCastException: android.app.Application context can not be cast to android.app.Activity
So I changed getApplicationContext()
to this
. and it worked fine:
CustomAdapter adapter = new CustomerAdapter(this,R.layout.listview_item_row, weather_data);
So, my question is : 1. why we can't pass Application context here? (for the customadapter). and
2. Which are the scenarios in which we must have to pass Activity context instead of Application context?
[Note: I have already read some answers here and here, but they do not concern with specific issue here. All are saying that 'you can use any of them', but in specific situation like this, it does not work. So, please do not mark as duplicate.]
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/25923400/context-parameter-for-custom-adapter-getapplicationcontext-fails-but-this