After doing many hit and try method and observing other stackoverflow code, I was able to send data to next activity. I want to know: Is it safe to call cursor.moveToPosition twice in onBindViewHolder method.
public class recyclerViewSongAdapter extends RecyclerView.Adapter<recyclerViewSongAdapter.MyViewHolder> {
private final Activity callingActivity;
private final Cursor songCursor;
public recyclerViewSongAdapter(Activity activity, Cursor cursor) {
callingActivity = activity;
songCursor = cursor;
if(songCursor != null) {
songPathIndex = songCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
songTitleIndex = songCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
songAlbumIndex = songCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM);
}
}
public class MyViewHolder extends RecyclerView.ViewHolder { //implements View.OnClickListener{
public TextView titleTextView, albumTextView;
public View parentLayout;
public MyViewHolder(View view) {
super(view);
titleTextView = view.findViewById(R.id.songTitleId);
albumTextView = view.findViewById(R.id.songAlbumId);
parentLayout = view.findViewById(R.id.parentLinearId);
}
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.song_element, viewGroup, false);
return new MyViewHolder(itemView);
}
public String songTitle, songAlbum;
int songPathIndex, songTitleIndex, songAlbumIndex;
@Override
public void onBindViewHolder(@NonNull final MyViewHolder myViewHolder, final int position) {
if(songCursor != null) {
songCursor.moveToPosition(position);
songTitle = songCursor.getString(songTitleIndex);
songAlbum = songCursor.getString(songAlbumIndex);
myViewHolder.titleTextView.setText("" + songTitle);
myViewHolder.albumTextView.setText("" + songAlbum);
myViewHolder.parentLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
songCursor.moveToPosition(position);
string title = songCursor.getString(songTitleIndex);
Intent intent = new Intent(callingActivity.getApplicationContext(), SongPlaying.class);
intent.putExtra("mayank", "" + title);
callingActivity.startActivity(intent);
}
});
}
}
@Override
public int getItemCount() {
return (songCursor == null) ? 0 : songCursor.getCount();
}
}
Edit: Earlier my question was how to send the title of clicked item to next Activity and now my question is using cursor.moveToPosition twice, a good idea.