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,438
  • 68
  • 55
  • 126
Sid
  • 582
  • 1
  • 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;
            }

    }
My God
  • 22,686
  • 26
  • 99
  • 179
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
  • 37,627
  • 12
  • 79
  • 103
5
Context context = parent.getContext();
Rohit5k2
  • 17,529
  • 8
  • 42
  • 56
Ajay Pandya
  • 2,397
  • 4
  • 30
  • 64