Reputation: 358
I have an array of items like:
items[0] = "Item 1";
items[1] = "Item 2";
...
And I fill my ListView list1 with this:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, items);
list1.setAdapter(arrayAdapter);
And I get the item value like this:
list1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String a = parent.getAdapter().getItem(position).toString();
...
And works, but I really need to store more values in each item. For example, I want an item called "First item" to appear in the list, but when I click it, I get an associate value, like a number.
Example:
items[0] = {7,"First item"};
items[1] = {100,"Second item"};
I want only the "First item" and "Second item" appearing in the list, but when I click it, I retrieve the integers, in this case, 7 for the "First item" and 100 for the "Second item".
How can I achieve something like this? Thanks!
Upvotes: 0
Views: 5879
Reputation: 8939
You can use HashMap
to store Key as First item and value as 7 and like wise.
String[] items = { "First item", "Second item", "Third item"};
HashMap<String, Integer> hashmap=new HashMap<String, Integer>();
hashmap.put("First item", 7);
hashmap.put("Second item", 100);
hashmap.put("Third item", 200);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, items);
list1.setAdapter(arrayAdapter);
list1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String textValue = parent.getAdapter().getItem(position).toString();
int value=hashmap.get(textValue);
System.out.println(textValue);
System.out.println(value+"");
}
O/P: When clicking on first item.
10-22 13:57:49.778: I/System.out(1038): First item
10-22 13:57:49.778: I/System.out(1038): 7
Hope this help you.
Upvotes: 3
Reputation: 1859
Why not store your return values in a second array?
items[0] = "first item";
items[1] = "second item";
value[0] = 7;
value[1] = 100;
Then grab the return value from the value array:
Log.i("SELECTED",item[position]);
Log.i("RETURNED",value[position]);
Upvotes: 1
Reputation: 496
You need to implement your custom adapter, instead of using the ArrayAdapter. There is a BaseAdapter class that you can implement and as an array of data you could use a SparseArray. SparseArrays are generic and provide getters by index, its exactly what you need to feed a ListView.
Upvotes: 1