I already asked a similar question here and one user suggested to subclass ArrayAdapter, but I have issues with that.
Here is my problem:
I use a HashMap<String, String> and a SimpleAdapter object to display user data in my ListView, but now I want to replace the HashMap<String, String> with an ArrayList<User>(); containing real user objects.
Here is the old code:
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_USERNAME, c.getString(TAG_USERNAME));
map.put(TAG_FIRSTNAME, c.getString(TAG_FIRSTNAME));
map.put(TAG_LASTNAME, c.getString(TAG_LASTNAME));
map.put(TAG_ADDRESS, c.getString(TAG_ADDRESS));
usersList.add(map);
[...]
ListAdapter adapter = new SimpleAdapter(this, usersList,
R.layout.single_user, new String[] { TAG_USERNAME,
TAG_FIRSTNAME, TAG_LASTNAME, TAG_ADDRESS },
new int[] { R.id.textViewUsername, R.id.textViewFirstName,
R.id.textViewLastName, R.id.textViewAddress });
Now, as suggested, I tried to subclass ArrayAdapter, but I have no plan how the getView(int, View, ViewGroup) should look like, to achieve my objective.
Here is my current code:
public class UserArrayAdapter extends ArrayAdapter<User> {
private Context mcon;
private List<User> userList;
public UserArrayAdapter(Context context, int resource,
List<User> userList) {
super(context, resource);
mcon = context;
this.userList = userList;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
for (User usr : userList) {
findViewById(R.id.textViewUsername).setText(usr.getFirstName());
}
return super.getView(position, convertView, parent);
}
}
Here is the User class:
public class User {
private String username, firstName, lastName, address;
public User(String username, String firstName, String lastName,
String address) {
setUsername(username);
setFirstName(firstName);
setLastName(lastName);
setAddress(address);
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
if (username == null) {
throw new IllegalArgumentException("username is null.");
}
this.username = username;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
if (firstName == null) {
throw new IllegalArgumentException("firstName is null.");
}
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
if (lastName == null) {
throw new IllegalArgumentException("lastName is null.");
}
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
if (address == null) {
throw new IllegalArgumentException("address is null.");
}
this.address = address;
}
}
And I thought I would call it like this:
ListAdapter ad = new UserArrayAdapter(this, R.layout.single_user, usersArrList);
Any help would be greatly appreciated.
Userclass