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

  • Spinner cannot load an integer array?
  • Android Battery usage profiling
  • Android Webkit: Absolutely positioned elements don't respect z-index
  • OpenCV Library error with AndroidStudio
  • Send notification to all the devices connected to a Wi-Fi network
  • How to maintain a paid and free version of an app
  • 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?

  • Sorting items position using FirebaseRecyclerAdapter
  • How to kill my own Activity - the hard way
  • Force RTL layout direction not working for app
  • What's the best way to debug RxJava problems with not received messages
  • How to get Android Local Service instance
  • How to change subtitle in mediaplayer
  • 2 Solutions collect form web for “Get Activity Context in an Adapter from a Fragment”

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

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.