Getting the android context in an adapter

android, android-adapter, android-context

Solution

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

- You only do it once, not every time, `getView()` is called.

- You can use it for other purposes too, when needed.

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

Problem

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 .

Original source