Diego
Diego

Reputation: 49

Populating ListView with ArrayList<Object>

I'm trying to populate a ListView with an ArrayList. The ArrayList contains Usuarios Objects. Usuario has two fields (String nombre, String edad). This is my code:

ListView listview = (ListView) findViewById(R.id.ListView1);
ArrayList<Usuario> listaUsuarios = (ArrayList<Usuario>) dao.showAll();

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

When I test my Android App, it looks like this:

enter image description here

The ListView doesn't show the Usuario fields (nombre, edad) it shows es.dga.sqlitetest.Usuario@43e4...

Can anyone help me? Thanks

Upvotes: 3

Views: 3979

Answers (4)

Swayam
Swayam

Reputation: 16354

Looks like you are calling the built-in toString() function on your Usuario objects.

You need to override it to implement your own in which you can retrieve the individual fields form the the objects (maybe by using something like mObject.getNombre() and mObject.getEdad() or just this.label).

Upvotes: 1

Hans Cappelle
Hans Cappelle

Reputation: 17495

What you see in your screenshot are the memory addresses of the objects from your list. The default behavior of the ArrayAdapter is to call the toString()method on each object in the array. If you don't override that toString() method you get the default with this result.

Quick Solution

Override the toString()method in your Usuario object:

class Usuario {
    // whatever you already had in place

    // the name to display in the list
    private String name = "some default value";

    public String toString(){
        return this.name;
    }
}

Better Solution

Create your custom adapter that has a collection of Usuarioobjects so you can inflate your view and display exactly the details that are needed. Some good information here and here.

Upvotes: 2

gunar
gunar

Reputation: 14710

You should provide a toString() method for Usuario. Something like:

@Override
public String toString() {
 return this.label;
}

Upvotes: 5

blganesh101
blganesh101

Reputation: 3695

hope this helps
http://developer.android.com/guide/topics/ui/layout/listview.html
Also look up ArrayAdapter interface:

  ArrayAdapter(Context context, int textViewResourceId, List<T> objects)

Upvotes: 0

Related Questions