经过多次尝试和尝试方法并观察了其他stackoverflow代码之后,我便能够将数据发送到下一个活动。 我想知道:在onBindViewHolder方法中两次调用cursor.moveToPosition是否安全。
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();
}
}
编辑:之前,我的问题是如何将单击项的标题发送到下一个活动,现在我的问题是两次使用cursor.moveToPosition,一个好主意。
答案 0 :(得分:0)
这不是在回收站适配器中使用游标的正确方法,但这是一种将当前标题发送到下一个活动的解决方案。
在您的onclick侦听器中编写以下代码
songCursor.moveToPosition(position);
String title= songCursor.getString(songTitleIndex);
Intent intent = new Intent(callingActivity.this,SongPlaying.class);
intent.putExtra("mayank", "" + title);
callingActivity.startActivity(intent);