如何从数据库删除中获取 ID 数据 - setOnLongClickListener 错误

How to get id data from database deleting - setOnLongClickListener ERROR

我有一个 recyclerview 和 sql 精简版数据库。我将城市名称保存在 SQLite 数据库中,并在 recyclerview 中显示它们。当城市在 recyclerview 中设置了 setOnclickListener 时,城市的天气就会显示出来,我通过从 sql lite 数据库中获取城市的 id 来做到这一点。

arrayList.get(position).id

它在 setOnClickListener 中有效,但在 setOnLongClickListener 中无效

我想在长按时删除recyclerview中的城市名称,但没有删除,因为它不起作用。

这个错误出现在 logcat : " java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 " 或类似的东西

我该如何解决这个问题?

我的适配器class

public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder>  {

ArrayList<City> arrayList;
Context context;
SQLiteDatabase db ;
Cursor cursor;
int dbId;



public Adapter(ArrayList<City> arrayList ,Context context ){
    this.arrayList = arrayList;
    this.context = context;

    db = context.openOrCreateDatabase("City",MODE_PRIVATE,null);


}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    RecyclerviewRowBinding recyclerviewRowBinding = 
    RecyclerviewRowBinding.inflate(LayoutInflater.from(parent.getContext()),
    parent,
    false);
    return new MyViewHolder(recyclerviewRowBinding);

}

@Override
public void onBindViewHolder(@NonNull Adapter.MyViewHolder holder, int position) {

    holder.binding.MytxtCities.setText(arrayList.get(position).cityName);


    holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setIcon(R.drawable.warningicon);
            builder.setMessage("Are you sure that you want to delete "+arrayList.get(position).cityName);
            builder.setPositiveButton("Ok", (dialog, which) -> {

                arrayList.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position,arrayList.size());

                dbId = arrayList.get(position).id; // <---the error is in this code
                System.out.println("dbId"+dbId);

                //db.execSQL("DELETE FROM city WHERE id ='" + arrayList.get(position).id + "'");


                cursor = db.rawQuery("SELECT * FROM city WHERE id=?",new String[]{String.valueOf(dbId)});
                Result(cursor);



            }).setNegativeButton("Cancel", (dialog, which) -> {

                //doing nothing
            }).show();


            return true;
        }


    });


    holder.itemView.setOnClickListener(v -> {

        Intent intent = new Intent(holder.itemView.getContext(),MainActivity.class);
        intent.putExtra("citId",arrayList.get(position).id); // <-- it works very well here and sends with intent
        holder.itemView.getContext().startActivity(intent);
    });
}


private void Result(Cursor cursor){

    if(cursor.getCount() > 0){

        db.delete("city","id=?",new String[]{String.valueOf(dbId)});
        notifyDataSetChanged();
    }
    else{
        Toast.makeText(context,"something went wrong !",Toast.LENGTH_LONG).show();
    }


}


@Override
public int getItemCount() {
    return arrayList.size();
}



public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView Mytxt_cities;
    private RecyclerviewRowBinding binding;

    public MyViewHolder(@NonNull RecyclerviewRowBinding binding) {
        super(binding.getRoot());
        this.binding = binding;
        Mytxt_cities = itemView.findViewById(R.id.Mytxt_cities);



    }


 }
 }

你的代码中有

arrayList.remove(position);

下面几行

dbId = arrayList.get(position).id; // <---the error is in this code

你的数组列表在 remove 调用后为空,但你仍在尝试在 position 处获取此项目,因此你得到 IndexOutOfBoundsException: Index: 0, Size: 0 - 你正在尝试获取项目在 position = 0 且数组为空

在从数组

中删除之前尝试移动获取dbId
            dbId = arrayList.get(position).id;
            arrayList.remove(position);
            notifyItemRemoved(position);
            //notifyItemRangeChanged(position,arrayList.size()); // this line is unnecessary