Search code examples
androidandroid-adapterandroid-context

Getting the android context in an adapter


In many of the code samples that I find on the internet the context is obtained in the constructor of an adapter.

This context is used to get an inflater to inflate the views in getView method.

My Question is why bother getting the context in the constructor when it can easily be obtained like so

        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;
        }

Also is there any reason not to use the above method because it till now I have not faced any problem in using it .


Solution

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