I have an array of User objects. I am only showing First Name and Last Name (through toString() method that I have implemented) in a List View.
public class User
{
public int UserID;
public String FirstName;
public String LastName;
@Override public String toString() {
StringBuilder result = new StringBuilder();
result.append(this.FirstName + " " + this.LastName);
return result.toString();
}
}
I am using the following adapter definition to bind the array of User objects to a List View.
ArrayAdapter<User> adapter = new ArrayAdapter<User>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, users); // Users is defined as User[] users; somewhere in the code.
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener ()
{
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// Here I would like to get the UserID
}
});
If you need more background. My array of User objects (users) is filled through a ksoap2 Webservice call. I understand that if I was using SimpleCursorAdapter, long id in public void onItemClick(AdapterView parent, View view, int position, long id) would automatically be the id that I am interested in. But that is not the case. Any help will be appreciated very much.
You just need to get the User
object from the list.
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
User user = (User)parent.getItemAtPosition(position);
long userId = user.UserID;
}
If you want the long id
to be the correct ID of the User, then you will need to override getItemId
of ArrayAdapter
. Ex:
ArrayAdapter<User> adapter =
new ArrayAdapter<User>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, users){
@Override
public long getItemId(int position){
return getItem(position).UserID;
}
};
I didn't test this, but I think it should work. I also wouldn't recommend using users[position]
. It is better to rely on getItem(position)
in case the underlying data changes from your original User
array.