Context for RecyclerView.Adapter

android, android-adapter, android-context

Solution

I've seen a lot of code where people keep reference to the Context in an Adapter. But in a RecyclerView.Adapter, the itemView (the view you already inflated from onCreateViewHolder) is accessible from your ViewHolder. For the most part, you should be dealing with the viewHolder anyways. So, use viewholder.itemView.getContext();. You can even expose a method in your viewholder getContext().

public Context getContext() {return itemView.getContext();}

Problem

I want to add `ProgressDialog` in an adapter. AFAIK, `.this` for activity, and `getActivity.getApplicationContext()` for fragment. What about adapter? Is it possible? I got error `Unable to add window -- token null is not valid; is your activity running?` when I use `mContext.getApplicationContext()`. EDIT: In a fragment, I show cards by ``` allGroupsView = (RecyclerView) rootView.findViewById(R.id.allGroupsView); adapterGroup = new AdapterGroup(getActivity().getApplicationContext(), results); allGroupsView.setAdapter(adapterGroup); allGroupsView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext())); ``` In class `AdapterGroup` ``` public class AdapterGroup extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context mContext; private LayoutInflater inflater; List<DataGroup> data= Collections.emptyList(); DataGroup current; public AdapterGroup(Context context, List<DataGroup> results) { this.mContext = context; inflater = LayoutInflater.from(mContext); this.data = results; } // Inflate the layout when viewholder created @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.card_view_row, parent, false); final MyHolder holder = new MyHolder(view); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("debug", String.valueOf(holder.getAdapterPosition())); getDetails(Config.GET_GROUP_DETAILS_URL, data.get(holder.getAdapterPosition()).groupName, data.get(holder.getAdapterPosition()).description); } }); return holder; } private void getDetails(String url, String groupName, String description) { groupName = groupName.replace(" ", "%20"); description = description.replace(" ", "%20"); final String finalGroupName = groupName; final String finalDescription = description; class GetDetails extends AsyncTask<String, Void, String> { ProgressDialog loading; @Override protected void onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(mContext.getApplicationContext(), null, "Please wait", true, true); loading.setCancelable(false); } // more code down from here ```

Original source