0

Up front: This is my first attempt at an Android app. I'm in that strange place of not knowing what to search for to find the answer to my question.

What I have accomplished is:

  • Created a custom class myCustomClass with properties of 'title' and 'youTubeUrl'
  • Created an ArrayList<myCustomClass>
  • Added multiple elements to ArrayList<myCustomClass>
  • Created a custom ArrayAdapter and attached it to the the arraylist.
  • Added an onItemClickListener to the custom ArrayAdapter.

All of that works good. I would like to show the title in the ListView and then when the user clicks the list view item, I'd like to get a reference to the youtubeUrl property.

Here's what I have for the adapter code:

MyListAdapter myListAdapter = new MyListAdapter(this, R.layout.my_list, elements);
myList.setAdapter(myListAdapter);
myList.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String item = ((TextView)view).getText().toString();
        Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
    }
});
myListAdapter.notifyDataSetChanged();

Thanks for your help.

il_guru
  • 8,383
  • 2
  • 42
  • 51

2 Answers2

1

You can use the position property in onItemClick to go back to your data source and find the relevant item. From there you should be able to retrieve the Url.

cjk
  • 45,739
  • 9
  • 81
  • 112
  • Thanks. I was able to get the youTubeUrl with this code: `String youTubeUrl = elements.get(position).youtubeVideo; Toast.makeText(getBaseContext(), youTubeUrl, Toast.LENGTH_LONG).show();` – Dave Rogers Jun 25 '12 at 15:28
0

As another poster implied, it depends on what you are using in your adapter. Assuming it's MyCustomClass. You can do something like this in your onItemClick method:

MyCustomClass selection = (MyCustomClass) getListView().getItemAtPosition(position);
Nick
  • 8,181
  • 4
  • 38
  • 63
  • Thanks for this. It might make the code more readable in the future. Am I correct in assuming that you code would end up getting the same data as this: `MyCustomClass selection = (MyCustomClass) elements.get(postion);` – Dave Rogers Jun 25 '12 at 15:38
  • I believe so. One note - adapters are often dynamic things so I probably wouldn't reference elements from within onItemClick(). If elements is marked final and you know for certain that you won't be changing your adapter's model it wont cause a problem but its still not a good idea. – Nick Jun 26 '12 at 14:28