1

I have a listview

ListView poiList = (ListView) findViewById(R.id.poiList);

and im populating it with

SimpleAdapter adapter = new SimpleAdapter(this, data,
                        android.R.layout.simple_list_item_2,
                        new String[] {"name", "dist"},
                        new int[] {android.R.id.text1,
                                   android.R.id.text2});
        poiList.setAdapter(adapter);

With this SimpleAdapter, there's an item and a subitem for each row in the ListView. Everything works perfectly.

Now I implement onItemClick for my ListView:

poiList.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {

            String poiName = ((TextView)view).getText().toString();
}
 }

But I cant get the text in the row that I selected. I think There's more than a single TextView in that row ( Item and subitem). How can I refer to them?

Mattia
  • 47
  • 1
  • 9
  • 3
    did you try view.findViewById(...)? – Kgrover Apr 02 '13 at 20:42
  • The view is passed automatically as a parameter when clicked, and is referred as "view" in the code. I dont know how can I extract the text from it, more specifically how can i extract the two strings (item, subitem) – Mattia Apr 02 '13 at 20:48
  • I expected somenthing like view.getText1() /view.getText2() or view.getItem() / view.getSubitem() – Mattia Apr 02 '13 at 20:51
  • 1
    The View is the listItem itself, and not the TextView. You have to call findViewById() in order to get the actual TextView. You assigned that TextView an id when you initialized the SimpleAdapter. – Kgrover Apr 02 '13 at 20:52
  • @Mattia check my answer. i explained that. – Simon Dorociak Apr 02 '13 at 20:54
  • Solved, thanks, you were so right (im stupid) String poiName = ((TextView) view.findViewById(android.R.id.text1)).getText().toString(); – Mattia Apr 02 '13 at 20:58
  • @Mattia I have posted an answer, so hopefully you can accept it as correct since it solved your problem. Thanks – Kgrover Apr 02 '13 at 23:01

2 Answers2

5

As I commented when you posted the question, you should use:

((TextView)(view.findViewById(android.R.id.text1))).getText().toString()

since the View is not the TextView itself, but the List Item's View.

Glad it solved your problem, by the way. Cheers.

Georg
  • 378
  • 1
  • 3
  • 10
Kgrover
  • 2,106
  • 2
  • 36
  • 54
-2

To make it complete:

String selectedFromList = ((TextView (view.findViewById(android.R.id.text1))).getText().toString(); 
ZygD
  • 22,092
  • 39
  • 79
  • 102
Wil
  • 351
  • 3
  • 9
  • This answer directly copies the accepted answer and as a result doesn't add anything that helps further readers of this question. In future if you notice that that what you have posted an identical answer to one already posted then it is good etiquette to remove your duplicate answer. – Joel Apr 03 '15 at 16:20