14

I have a class named BinderData which extends BaseAdapter. I want to get the base class context. I tried to use getContext() but that doesn't work in case of BaseAdapter.

How can I get the Context of this class?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sid
  • 582
  • 3
  • 7
  • 28

3 Answers3

32

One more solution-

If you have a parent, you can directly access the context like so-

 public class SampleAdapter extends BaseAdapter {

            LayoutInflater inflater;

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if(inflater == null){
                Context context = parent.getContext();
                inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                }
                ...
                ...

                return convertView;
            }

    }
sjain
  • 23,126
  • 28
  • 107
  • 185
14

Make a constructor that takes a Context as one of its arguments and store it in a private variable.

public class SampleAdapter extends BaseAdapter {
    private Context context;

    public SampleAdapter(Context context) {
        this.context = context;
    }

    /* ... other methods ... */
}
Karakuri
  • 38,365
  • 12
  • 84
  • 104
6
Context context = parent.getContext();
Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
Ajay Pandya
  • 2,417
  • 4
  • 29
  • 65