Good afternoon! What day I rack my brains I can't understand why this is happening :( When you delete the last position with a swipe, the first one is deleted, this happens only with the last position.
private NotesAdapter notesAdapter;
private AlertDialog dialogURL;
private static ArrayList<Note> notesFromDB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(v -> {
if (!isClick) {
DetailNoteActivity.start(MainActivity.this, null);
isClick = true;
}
});
RecyclerView recyclerViewNotes = findViewById(R.id.rv_notes);
recyclerViewNotes.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
notesFromDB = new ArrayList<>();
notesAdapter = new NotesAdapter();
MainViewModel viewModel = new ViewModelProvider(this).get(MainViewModel.class);
viewModel.getNotes().observe(this, notes -> {
notesFromDB = (ArrayList<Note>) notes;
notesAdapter.setItems(notesFromDB);
});
...
private final ItemTouchHelper.SimpleCallback simpleCallback =
new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView,
@NonNull RecyclerView.ViewHolder viewHolder,
@NonNull RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
App.getInstance().getNoteDao().deleteNote(notesFromDB.get(position));
notesAdapter.notifyItemRemoved(position);
}
};
Adapter
public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.NoteViewHolder> {
private final SortedList<Note> sortedList;
public NotesAdapter() {
sortedList = new SortedList<>(Note.class, new SortedList.Callback<Note>() {
@Override
public int compare(Note o1, Note o2) {
if (!o2.isDone() && o1.isDone()) {
return 1;
}
if (o2.isDone() && !o1.isDone()) {
return -1;
}
return (int) (o2.timestamp - o1.timestamp);
}
...
Any help would be greatly appreciated.
Add to adapter:
} ...
With swipe: