Why not make ArrayAdapter member variable


#1

We have code that defines the ArrayAdapter inside onCreate() method:

[code]
public class CrimeListFragment extends ListFragment {
private ArrayList mCrimes;

@Override
public void onCreate(Bundle savedInstanceState){
	super.onCreate(savedInstanceState); // call super-class method
	getActivity().setTitle(R.string.crimes_title);
	...
	// create ArrayAdapter (to handle views or each crime in list)
	ArrayAdapter<Crime> adapter = new ArrayAdapter<Crime>(getActivity(), android.R.layout.simple_list_item_1, mCrimes);
	setListAdapter(adapter);
}

}
[/code]

And then when we need to use the adapter (in Listing 9.17) we “get” the ListAdapter:

[code]@Override
public void onListItemClick(ListView l, View v, int position, long id){
	Crime c = (Crime)getListAdapter().getItem(position);
}[/code]

So, why don’t we just make adapter a member variable and then access it that way? Is it just a style preference?

[code]public class CrimeListFragment extends ListFragment {

private ArrayList<Crime> mCrimes;
private ArrayAdapter<Crime> mAdapter;

@Override
public void onCreate(Bundle savedInstanceState){
	super.onCreate(savedInstanceState); // call super-class method
	getActivity().setTitle(R.string.crimes_title);
	...
	// create ArrayAdapter (to handle views or each crime in list)
	mAdapter = new ArrayAdapter<Crime>(getActivity(), android.R.layout.simple_list_item_1, mCrimes);
	setListAdapter(mAdapter);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id){
	Crime c = (Crime)mAdapter.getItem(position);
}

}[/code]


#2

Yes, that’d be a perfectly fine approach. We’ve used it frequently in our own code - I don’t hold a strong opinion about whether or not to do it.