开发者

Storing data on ListView item

开发者 https://www.devze.com 2023-01-19 08:13 出处:网络
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.

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 ArrayAd开发者_如何学Capter. 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.


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();
    // ...
}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号