Getting the android context in an adapter

Obtaining the Context in the constructor has (at least) three advantages:

  1. You only do it once, not every time, getView() is called.
  2. You can use it for other purposes too, when needed.
  3. It also works, when parent is null.

However, if you don't have any problems with your solution, you might as well stick to it.


Here is an example:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;
    Holder holder;
    if (view == null) {
        view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_job, parent, false);
        holder = new Holder(view, this);
        view.setTag(holder);
    } else {
        holder = (Holder) view.getTag();
    }

    holder.parse(getItem(position), position);
    return view;
}

public class Holder {

    @Bind(R.id.type)
    TextView type;
    @Bind(R.id.date_time)
    TextView dateTime;
    @Bind(R.id.grade)
    TextView grade;

    public Holder(View view) {
        ButterKnife.bind(this, view);
    }

    public void parse(final GetGradeHistoryResponse.GradeHistory item) {
        if (item.grade < 0) {
            grade.setTextColor(App.getInstance()
                    .getResources().getColor(R.color.withdraw_status));
            grade.setText(String.valueOf(item.grade));
        } else {
            grade.setTextColor(App.getInstance()
                    .getResources().getColor(R.color.primary));
            grade.setText("+" + String.valueOf(item.grade));
        }

        type.setText(item.type);
        dateTime.setText(item.datetime);
    }
}

You can get context by view.getContext() in the Holder