Question

I have a class who creates an Arraylist. By this class, I add/remove objects. I have no problem to populate a spinner, but when I come by using a listview, it is always empty.

How I populate a spinner:

final ArrayAdapter<Object> adapterEleves;
adapterEleves = new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, ArraylisteEtudiants.getListe());

Spinner spinnerEtudiants = (Spinner) findViewById(R.id.spinnerEtudiants);
spinnerEtudiants.setAdapter(adapterEleves);
adapterEleves.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

How I try to populate a listview with multiple choices:

    final ArrayAdapter<Object> adapterEleves;
    adapterEleves = new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_multiple_choice, ArraylisteEtudiants.getListe());

    ListView listEtudiants = (ListView) findViewById(R.id.afficherListeEtudiants);
    listEtudiants.setAdapter(adapterEleves);
    adapterEleves.setDropDownViewResource(android.R.layout.simple_list_item_multiple_choice);

My xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >

    <ListView
      android:id="@+id/afficherListeEtudiants"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:choiceMode="multipleChoice" >
    </ListView>

</LinearLayout>

My arraylist class:

public class ArraylisteEtudiants {

    final static ArrayList<Object> listeEtudiants = new ArrayList<Object>();

    public static ArrayList<Object> getListe() {

        return listeEtudiants;
    }
}

Thanks in advance! :)

Was it helpful?

Solution

According to Android reference:

ArrayAdapter

By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

I'm pretty sure your ArrayAdapter doesn't provide a toString() method and that's why it will show you a blank list.

You can simply override that method in your returned object (try to use a more specific type rather than Object).

If this cannot solve your problem, you should give a try to custom ArrayAdapter, extending ArrayAdapter, personalizing the getView() method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top