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

Asked

Viewed 322 times

1

I have a Webservice that lists all my users and brings users from 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 play all of this on a Listview. I got it. But I managed using an Arrayadapter of Strings and a list of String, IE, step only the name.

How will I be able to associate this name with your bank id so I can recover change the screen 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 same Listview, just show the name. But I have to filter on the other screen by id using putextra, etc.

My difficulty is to associate the ID to the Name, I’ve tried creating a list of Users, but it’s not the way I want it.

And now what I do?

  • when we ignite an Adapter our list is listed with a position, when the method OnItemClickListener() is called, it will know which position of the list was selected, at the moment I can not put an example, but as soon as possible I put here.

1 answer

4


How do you intend only that the list present the nome a simple way is to do the Override of the method toString() of your class User:

public class Usuario {
    int id;
    String nome;
    .....
    .....
    @Override
    public String toString() {
        return nome;
    }
}  

Note: The Arrayadapter uses the method toString() of the object it contains to obtain the value to be displayed in the list.

Then use normally, 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);  

In the onItemClick() you can get the 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 well: Although in this case the correct way would be to implement a custom Adapter.

  • Sorry for the delay. But it worked perfectly. Thank you very much! Peace and light!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.