Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Activity Context in an Adapter from a Fragment

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?

like image 898
AdrianoCelentano Avatar asked Jun 03 '13 13:06

AdrianoCelentano


People also ask

How do you get the activity context inside a fragment?

You can use the getActivity() method to get context or You can use getContext() method .

How can we get parent activity context from fragment?

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.

How do I get the context of another activity?

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).


2 Answers

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.

like image 198
daniel_c05 Avatar answered Sep 25 '22 09:09

daniel_c05


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.

like image 28
Michał Z. Avatar answered Sep 21 '22 09:09

Michał Z.