Bring only the name in the ListView, but relate to the ID

1

I have a WebService that lists all my users and brings users to the bank.

I have a class

Usuario {
int id;
String nome;
}

With its builders, gets and sets, etc.

And I can return all my users.

However, I want to throw all this in a ListView. I got it. But I managed using an ArrayAdapter of Strings and a list of String, that is, I just step the name.

How can I associate this name with your bank id to be able to recover screen changes using the OnItemClickListener () event, if I just pass the name?

Can you do this without having to display the id on the screen? (without using two textviews, etc.).

I want to use a ListView myself, just show the name. But I have to filter on the other screen by id using the putextra, etc.

My problem is to associate the ID with the Name, I've already tried creating a list of Users, but it does not go the way I want.

And now, what do I do?

    
asked by anonymous 23.06.2015 / 02:18

1 answer

4

As you just want the list to show nome a simple way is to override the toString() method of your User class:

public class Usuario {
    int id;
    String nome;
    .....
    .....
    @Override
    public String toString() {
        return nome;
    }
}  
The ArrayAdapter uses the toString() method of the object it contains to get the value to display in the list.

.

Then it is usually used, only instead of ArrayList<String> is ArrayList<Usuario> :

ArrayList<Usuario> usuarios = new ArrayList<Usuario>();

ListView listView = (ListView) findViewById(R.id.list);

ArrayAdapter<Usuario> adapter = 
            new ArrayAdapter<Usuario>(this, android.R.layout.simple_list_item_1, usuarios);
listView.setAdapter(adapter);  

No onItemClick() you can get id of the item clicked as follows:

listview.setOnItemClickListener(new OnItemClickListener(){
    @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id){
        Usuario usuario = (Usuario)parent.getAdapter().getItem(position);
        String id = usuario.getId();
    }
});

Note: Although in this case the correct way would be to implement a custom adapter .

    
23.06.2015 / 16:01