8

I have a listView vith some items.

I would like to get from my onClickListener the name (String) of the selected item.

I know how to get the selected position but how to find the String of this element?

Here is my on click listener:

journalNames.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
    {

    }});

My listView is populated with some query from the database.

Thank you.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Milos Cuculovic
  • 19,631
  • 51
  • 159
  • 265

2 Answers2

19

What about,

journalNames.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
    {
      String selectedFromList = (journalNames.getItemAtPosition(position).getString());
    }});
Milos Cuculovic
  • 19,631
  • 51
  • 159
  • 265
user370305
  • 108,599
  • 23
  • 164
  • 151
  • i think the getItemAtPosition()do not return a String – Dany's Feb 24 '12 at 08:52
  • 1
    Amazing, great answer. That's exactly what I needed. Thank you so much. Only add .getString() at the end. – Milos Cuculovic Feb 24 '12 at 08:53
  • 1
    you can use like this, String selectedFromList = (String)journalNames.getItemAtPosition(position); or String selectedFromList = (journalNames.getItemAtPosition(position).toString()); – user370305 Feb 24 '12 at 08:58
8

YOu can find it either on view or on parent. In eclipse just type view. and see what methods you get after you type .(dot). I think this is the best.

parent.getAdapter().getItem(position);
Dany's
  • 943
  • 1
  • 7
  • 17
  • 1
    Since your adapter/list may contain more information (e.g. Ids) than are displayed within your list item view, I vote for this answer. – David Jun 15 '13 at 22:17
  • It must be this way! I always directly accessed list (as a field in class) but I was wrong. Through parent the listener gets encapsulated. Even I had to shift from one list to another, the listener can stay unchanged! – user1592714 Nov 14 '13 at 00:40