views:

59

answers:

3

First of all I'm new to Anroid. 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.

A: 

I would recommend using the Intent to pass only the id of the selected user. In your second activity you can use that id to fetch the rest of the information from your database or whatever you are using. Intents are not really suited to sending large amounts of data.

Computerish
Yeah, that's what I'm planning to do. But to understand which item is clicked, that item and user record must be associated. So my question is how can I associate that User record with a ListView item.
pocoa
A: 

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();
    // ...
}
Andy
+1  A: 

Assuming you already have an array list populated with data you want:

ArrayList<User>

So in your custom ArrayAdapter class, you should have these:

private ArrayList<User> items;
private Context context;

public UserAdapter (Context context, int textViewResourceId, ArrayList<User> items) {
                super(context, textViewResourceId, items);
                this.items = items;
                this.context = context;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
     User u = items.get(position);
     // Then you can get each user detail and 
     // display it however you like in your view
     u.getId();
     u.getName();
     // Assuming you have setters and getters setup in your User class
     return view;
}

In your OnClickItemListener, you can use "position" to determine which item is clicked and use it to retrieve the User object. You should be able to retrieve the other details once you have it.

Shane Oliver