Achraf Khouadja Achraf Khouadja - 24 days ago 11
Android Question

Create a listView adapter from hashtable containing an object as value

im very newbie in android & java
and I have a hashtable that contains values.
values are objects (task class that has 3 attributes code,title,state)

I'm trying to get the data of all tasks in hashtable and show them in list view

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

ArrayList<task> arr = new ArrayList<task>(tasklist.values());

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.list, arr );

list.setAdapter(arrayAdapter);


tasklist
is hashtable name

task
is an entity class

public class taskDAO {
public static final Hashtable<Integer , task> tasklist = new Hashtable<Integer , task>();

public static final boolean addTask (task t){

tasklist.put(t.code,t);
return true;

}


Exception


E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView


I tried many things but since i dont get how this works i can't figure out
a solution,
any help?

Answer

Your error is telling you that the second argument to the Adapter needs to be a TextView layout, not a ListView layout (or whatever the list.xml file contains)

If you implement a toString method on your task class (which you should rename to Task because of Java naming conventions).

Then, you'll see data when you use

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
    this, 
    android.R.layout.simple_list_item_1, 
    arr);

For more details about that layout, see What is "android.R.layout.simple_list_item_1"?

Comments