Skip to content Skip to sidebar Skip to footer

Android: How To Pass Data From An Adapter To The Main Activity From A Onclicklistener

I am really stuck here, I am 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

Solution 1:

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

interfaceOnItemClickListener {
    voidonItemClicked(int position);
}

in activity:

privateOnItemClickListenerlistener=newOnItemClickListener() {
    publicvoidonItemClicked(int position) {
        Songsong= adapter.get(position);
        //do whatever you want with song
    }
}

//creation of adapterSongAdapteradapter=newSongAdapter(this, songs, listener);

in adapter:

privateOnItemClickListener onClickListener;

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

//in getView
addToPlaylistButton.setOnClickListener(newView.OnClickListener() {
        @OverridepublicvoidonClick(View view) {
            if (onClickListener != null) {
                onClickListener.onItemClicked(position);
            }
        }
    });

Solution 2:

You can just use the reference to the songs that you pass to the adapter when you create it. Something like this:

classSongAdapterextendsArrayAdapter<Song> {

    private ArrayList<song> songs;

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

    (snip...)

        @OverridepublicvoidonClick(View view) {
            intposition= (Integer) view.getTag();
            Songsong= getItem(position);

            songs.add(song);
            (...)
        }
    }); // end of listener

}
}

And your ArrayList will now contain your Song.

Another, simpler way to do this would be to make the ArrayList in the main Activity static, so you can refer to it from anywhere, however, this is not recommended on Android.

Post a Comment for "Android: How To Pass Data From An Adapter To The Main Activity From A Onclicklistener"