I am making a todo list app where if I click on an item in a RecyclerView
a Dialog
will pop up that lets you edit the name of that task. On some tasks when I accept the changes the app crashes and this stack trace pops up.
10-02 15:10:34.801 9701-9701/com.gigstudios.todolist E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gigstudios.todolist, PID: 9701
java.lang.ArrayIndexOutOfBoundsException: length=10; index=-1
at java.util.ArrayList.get(ArrayList.java:310)
at com.gigstudios.todolist.RecyclerListAdapter$3$1.onInput(RecyclerListAdapter.java:166)
at com.afollestad.materialdialogs.MaterialDialog.onClick(MaterialDialog.java:370)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21163)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
This is the line where it crashes because getAdapterPostion
returns -1:
taskList.getTasks().get(holder.getAdapterPosition()).setTitle(input.toString().trim());
I cant seem to find any pattern on which items crash and why others don't.Here is the full code for the onBindViewHolder
.
@Override
public void onBindViewHolder(final ItemViewHolder holder, final int position) {
//other code
//edit task
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new MaterialDialog.Builder(context)
.title(R.string.edit_task)
.inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES)
.inputRange(0, 300)
.positiveText(R.string.save)
.negativeText(R.string.cancel)
.input(context.getString(R.string.task_title), holder.textView.getText().toString(), new MaterialDialog.InputCallback() {
@Override
public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
//Edit Task
taskList.getTasks().get(holder.getAdapterPosition()).setTitle(input.toString().trim());
notifyItemChanged(holder.getAdapterPosition());
//save
save();
}
}).show();
}
});
}
Why is this happening?