Search code examples
javaandroidlistviewlistviewitem

Storing data on ListView item


First of all I'm new to Android. So it might be a very simple question but I couldn't find the answer by myself.

I have two Activity, I'm filling the first one with the user names and the other data I receive from the remote request and the second one is being used to display the details of the selected user.

So in some way I need to associate those User records with the ListView items, so I can pass some of these information the the second Activity using an Intent. I'm not sure if it's right or wrong but I found that I need to create a custom ArrayAdapter. So I've created a User class:

class User {
   public String id;
   public String name;
}

and I guess now I need to write something like:

class UserAdapter extends ArrayAdapter<User> {
   ...
}

Basically in the first view I want to display:

John Doe
Mike Brown
...

Second one will make another request based on User.id and display some information about the user like:

John Doe, 45, San Francisco

I couldn't find a similar example so I'm not very sure about how can I do that. Any reference would also be helpful.

Thanks.


Solution

  • In the "getView" method of your UserAdapter, set the tag of the view to something useful...

    view.setTag(id);
    

    Then you can pull this information out when something is clicked...

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Integer id = (Integer) view.getTag();
        // ...
    }