I have a Fragment with a ListView. In the adapter I want to create a dialog.
class ViewHolder {
...
@Override
public void onClick(View v) {
...
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
...
}
...
}
mContext is the Context from my Fragment, which I save global when the adapter is created.
I get the error.
unable to add window -- token null is not for an application
The method getActivity() is not available so how to get the Context of my Activity?
You can use the getActivity() method to get context or You can use getContext() method .
You can get the parent activity from a Fragment by calling getActivity() . 💡Difference : Both getContext() and getActivity() are not much different in most cases, when you just need a context as both will get Parent activity context.
You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in a class that extends from Context, such as the Application, Activity, Service and IntentService classes).
If you have a custom adapter, change the constructor to require Context as a parameter.
public CustomAdapter(Context context, List<Item> items) {
}
Then, create an Instance variable to store the context via the constructor.
private Context mContext; //instance variable
public CustomAdapter(Context context, List<Item> items) {
//some code
this.mContext= context;
}
And now you can use the variable mContext from anywhere in your adapter.
To create the adapter, simply pass 'this' if created from an activity, or getActivity() if created from a fragment.
mAdapter = new CustomAdapter(this, mArrayItems);
Hope that helps.
When you are creating your adapter, what are you passing as a context? Try to pass this if you are not doing it. Some more code would be helpful too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With