Tyrone3 Tyrone3 - 1 year ago 124
Android Question

Android: How to pass Data from an Adapter to the Main Activity from a OnClickListener

im really stuck here, im new to Programming.
I achieved a lot in my Music App, but now i made a button in my listViewAdapter with a OnClickListener and i want to add a Song to the favList ArrayList in my MainActivity. With this code i have the Song i want, but how do i get it into the List?
Here is my code for this:

class SongAdapter extends ArrayAdapter<Song> {

SongAdapter(Context context, ArrayList<Song> songs) {
super(context, 0, songs);

public View getView(final int position, View convertView, @NonNull ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
Song currentSong = getItem(position);

TextView songNameTextView = (TextView) listItemView.findViewById(R.id.song_name);
assert currentSong != null;
TextView songArtistTextView = (TextView) listItemView.findViewById(R.id.song_artist);

ImageButton addToPlaylistButton = (ImageButton) listItemView.findViewById(R.id.addToPlaylist);
addToPlaylistButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int position = (Integer) view.getTag();
Song song = getItem(position);
Toast.makeText(view.getContext(), song.getAlbum().toString(), Toast.LENGTH_LONG).show();

return listItemView;
} }

And here are the parts from my MainActivity:

final ArrayList<Song> songs = new ArrayList<>(); final ArrayList<Song> favSongs = new ArrayList<>();

protected void onCreate(Bundle savedInstanceState) {
//Setup the Listview for the Songs
SongAdapter adapter = new SongAdapter(this, songs);
ListView listView = (ListView) findViewById(R.id.list);

Answer Source

You should create own OnItemClickListener in activity, set it to adapter and then dispatch onClick event with position to that custom listener.

interface OnItemClickListener {
    void onItemClicked(int position);

in activity:

private OnItemClickListener listener = new OnItemClickListener() {
    public void onItemClicked(int position) {
        Song song = adapter.get(position);
        //do whatever you want with song

//creation of adapter
SongAdapter adapter = new SongAdapter(this, songs, listener);

in adapter:

private OnItemClickListener onClickListener;

SongAdapter(Context context, ArrayList<Song> songs, OnItemClickListener onClickListener) {
    super(context, 0, songs);
    this.onClickListener = onClickListener;

//in getView
addToPlaylistButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            if (onClickListener != null) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download