I have a code structured as follows:
public class MyListFragment extends ListFragment {
private ArrayList<User> users;
private void initAdapter() {
if(users == null) return;
//getUserStatus(users); <———HERE 1
UsersAdapter adapter = new UsersAdapter(users);
setListAdapter(users);
getUserStatus(users); // vs <—— HERE 2
}
private void getUserStatus(List<User> users) {
final UsersAdapter adapter = (UsersAdapter )getListAdapter();
for(User user:users) {
Thread t = new Thread(new Runnable() {
//code to fetch some data
if ( adapter == null) Log.e(“App”, “Adapter is NULL!”);
});
t.start();
}
}
private UsersAdapter extends ArrayAdapter<User> {
public UsersAdapter(List<User> users) {
super(getActivity(), 0, users);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//code to inflate and populate list item
}
}
My question is:
Why if in my initAdapter
if I comment out getUserStatus
in the current version marked as HERE 2
and uncomment HERE 1
so that getUserStatus
is run before setListAdapter
the adapter
is always null
in getUserStatus
? I always see in the logs by all threads Adapter is NULL
?
It's simple. In HERE 1, you are trying to get the user related things from adapter you haven't initialized yet which is inialising using the function setListAdapters(users). In HERE 2, you are getting the users after initialising adapters, so it is working fine.