Android: Getting Text from Selected List Item

I spent a lot of time trying to figure out how to do a very simple thing – you have a list view and you select a particular item – i wanted to get the text associated with the selected list item – it ended up being more complex than i thought 🙂

Here is the code you will need in the AdapterView.OnItemClickListener to retrieve the textview and this code worked for me

private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position,
long id) {
Intent i = new Intent(MainActivity.this, CartoonListActivity.class);
TextView txt = (TextView) parent.getChildAt(position).findViewById(
R.id.title);
i.putExtra(“CartoonName”, txt.getText().toString());
startActivity(i);
}
};

Advertisements

3 Responses to Android: Getting Text from Selected List Item

  1. Ran into a problem with this code – could not debug it so came up with a work round

    problem: there was a Null Pointer Exception being thrown for some items in the list and not for some – weird problem but folks have faced it.
    http://stackoverflow.com/questions/10229460/onitemclick-of-items-in-listview-after-scrolling-throws-nullpointerexception

    Overcame it by retrieving the content from the adapter

    Override the following method in the adapter
    public Object getItem(int position) {
    return getListTextsIds()[position];
    }

    Call it from the Activity: adapter.getItem(position).toString() to get the text

  2. xrebootx says:

    Oh my god you saved my day! Should have found this 2 days ago. when i started searching for a solution! :p

  3. Jami says:

    I like the valuable information you provide in your articles.

    I will bookmark your blog and check again here frequently.
    I am quite certain I will learn plenty of new stuff right here!
    Best of luck for the next!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: