Android ArrayList item in ListView
-
25-06-2021 - |
Question
So I have this list which uses values from an ArrayList (and I can't use String[] because the user must add items to the list, and I can't do .add to the String[]). But now I have problems with onItemClick method. I want to get the text from item selected, and my book says the following should work:
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
dodaj.setText(values[arg2]);
}
But I get the following error: The type of the expression must be an array type but it resolved to ArrayList What should I do to fix it?
Solution
is "values" an ArrayList? if so use
dodaj.setText( (String)values.get( arg2 ) );
OTHER TIPS
you will have to convert arraylist to array using arraylist.toarray()
With ArrayList you always use
arrayList.get(index);
Recommended way is to add a toString() method to your items/Objects so that it returns the preferred field.
public Student()
{
...
...
public String toString()
{
return firstName + " " + lastName;
}
}
Now you can use arrayList.get(int index). It will print our the output of toString().