I have a custom ArrayAdapter I use to manage my ListView:
public class FilesAdapter extends ArrayAdapter<PutioFileLayout> {
Context context;
int layoutResourceId;
PutioFileLayout data[] = null;
public FilesAdapter(Context context, int layoutResourceId, PutioFileLayout[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
FileHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new FileHolder();
holder.textName = (TextView) row.findViewById(R.id.text_fileName);
holder.textDescription = (TextView) row.findViewById(R.id.text_fileDesc);
holder.imgIcon = (ImageView) row.findViewById(R.id.img_fileIcon);
row.setTag(holder);
} else {
holder = (FileHolder) row.getTag();
}
PutioFileLayout file = data[position];
holder.textName.setText(file.name);
holder.textDescription.setText(file.description);
holder.imgIcon.setImageResource(file.icon);
return row;
}
static class FileHolder {
TextView textName;
TextView textDescription;
ImageView imgIcon;
}
}
And in my Fragment, I declare these before the onCreate:
private PutioFileLayout[] fileData;
private FilesAdapter adapter;
Then, in the onCreate, I initialize it with this, as a placeholder for the user:
fileData = new PutioFileLayout[] {
new PutioFileLayout("Loading...", "Your files will appear shortly.", R.drawable.ic_launcher, false)
};
And I initialize my adapter:
adapter = new FilesAdapter(getSherlockActivity(), R.layout.file,
fileData);
listview.setAdapter(adapter);
Later, after some network stuff, I update the adapter’s data. This is where I think I might be going wrong.
PutioFileLayout[] files = blah blah, stuff. I've confirmed in debug that this array is correct and has the correct number of values.
adapter.data = files;
adapter.notifyDataSetChanged();
The result of all that is the ListView showing the very first item in the array, and nothing else.
If I add a second Loading… row or similar when I initialize it, it shows the first two. Etcetera.
Am I missing something? What’s the proper way to do this?
If you want to update
ArrayAdapteruseArrayListinstead ofArray. Because if you are usingArray,ArrayAdapterwill useListinternally which can’t be updated.Rewrite your constructor
In
getView()you get item by invokinggetItem(position).To initialize your adapter use
adapter = new FilesAdapter(getSherlockActivity(), R.layout.file, new ArrayList<PutioFileLayout>());And to fill your adapter use
adapter.add(new PutioFileLayout(...));