Search code examples
androidlistviewcrashsimpleadapter

Application crashes trying to retrieve view contents from ListView using SimpleAdapter


I am having an issue with trying to retrieve the contents of the view that the the user has clicked within a ListView. My ListView is setup using a SimpleAdapter and is comprised of a "heading" and a "sub-title" for each of the items in the list. These are stored using a HashMap.

Within the activity also, is a spinner, when the user selects an item in the spinner, the ListView is updated. This is working fine and I just thought it necessary to mention what is happening within the activity as well.

What I am trying to do, is retrieve which item the user has selected so I can guide them to a new activity based on their selection (right now just trying to display the view contents with Toast). I want to retrieve the contents of what is stored under the "engExp" key for the item.

Here is my code:

    // HASHMAP FOR LISTVIEW
    List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
    for(int x = 0; x < expressionListForModule.getCount(); x++) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("engExp", expressionListForModule.getString(0));
        map.put("japDef", expressionListForModule.getString(1));
        fillMaps.add(map);
        expressionListForModule.moveToNext();
    }

    // SETUP LISTVIEW
    SimpleAdapter adapter2 = new SimpleAdapter(this, fillMaps, android.R.layout.simple_list_item_2, new String[] {"engExp","japDef"}, new int[] {android.R.id.text1, android.R.id.text2});
    ListView lv = (ListView) findViewById(R.id.expressionList);
    lv.setAdapter(adapter2);
    lv.setTextFilterEnabled(true);
    lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_LONG).show();
        }
    });

Specifically, the item that is causing the application to crash is this: ((TextView) view).getText()

If you need to see any more of my code, please let me know.

Any help is appreciated, thanks in advance.


Solution

  • try

    lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TextView v = (TextView) view.findViewById(android.R.id.text1);
            String contentForLink = v.getText().toString();
            Toast.makeText(getApplicationContext(), contentForLink, Toast.LENGTH_LONG).show();
        }
    });