Android Studio中SQLite的ID始终返回0,如何用ID实现删除?
待办列表应用滑动删除时ID始终为0的问题解决
我在开发Android待办列表应用时遇到问题:滑动列表项删除时,获取到的ID始终为0,但数据库中实际存储了正确的ID。我希望通过ID实现删除操作,而非使用名称,相关代码如下:
MainActivity.java
package com.example.myapplication; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private EditText etEnterColor; private Button btnAddNote; private RecyclerView rvColors; private List<ColorsModel> colorsModelsList; private CustomColorsAdapter customColorsAdapter; ColorDatabaseHelper colorDatabaseHelper = new ColorDatabaseHelper(MainActivity.this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rvColors = findViewById(R.id.recyclerview_main_colors); etEnterColor = findViewById(R.id.editText_main_enterColors); btnAddNote = findViewById(R.id.button_main_add); loadAdapter(); addButton(); deleteSwipe(); } public void addButton(){ btnAddNote.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String extractColor = etEnterColor.getText().toString(); colorDatabaseHelper.createNote(new ColorsModel(extractColor)); loadAdapter(); etEnterColor.setText(""); } }); } public void loadAdapter(){ colorsModelsList = new ColorDatabaseHelper(MainActivity.this).readNote(); customColorsAdapter = new CustomColorsAdapter(colorsModelsList); rvColors.setAdapter(customColorsAdapter); } public void deleteSwipe(){ ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { @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) { Toast.makeText(MainActivity.this, "ID: " + colorsModelsList.get(viewHolder.getAdapterPosition()).getId(), Toast.LENGTH_SHORT).show(); colorDatabaseHelper.deleteNote(colorsModelsList.get(viewHolder.getAdapterPosition()).getId()); colorsModelsList.remove(viewHolder.getAdapterPosition()); customColorsAdapter.notifyItemRemoved(viewHolder.getAdapterPosition()); } }; ItemTouchHelper touchHelper = new ItemTouchHelper(simpleCallback); touchHelper.attachToRecyclerView(rvColors); } }
ColorDatabaseHelper.java
package com.example.myapplication; import android.annotation.SuppressLint; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import androidx.annotation.Nullable; import java.util.ArrayList; import java.util.List; public class ColorDatabaseHelper extends SQLiteOpenHelper { public static final String NAME = "colors.db"; public static final int VERSION = 1; public static final String TABLE_COLORS = "COLORS"; public static final String COLUMN_ID = "ID"; public static final String COLUMN_NAME = "NAME"; public ColorDatabaseHelper(@Nullable Context context) { super(context, NAME, null, VERSION); } @Override public void onCreate(SQLiteDatabase db) { String query = "CREATE TABLE " + TABLE_COLORS + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT);"; db.execSQL(query); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String query = "DROP TABLE IF EXISTS " + TABLE_COLORS + ";"; db.execSQL(query); onCreate(db); } public void createNote(ColorsModel colorsModel){ SQLiteDatabase sqLiteDatabase = getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(COLUMN_NAME, colorsModel.getName()); sqLiteDatabase.insert(TABLE_COLORS, null, contentValues); sqLiteDatabase.close(); } public List<ColorsModel> readNote(){ List<ColorsModel> colorsModelList = new ArrayList<>(); SQLiteDatabase sqLiteDatabase = getReadableDatabase(); String query = "SELECT * FROM " + TABLE_COLORS + ";"; Cursor cursor = sqLiteDatabase.rawQuery(query, null); cursor.moveToFirst(); while (!cursor.isAfterLast()){ @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex(COLUMN_ID)); @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME)); colorsModelList.add(new ColorsModel(name)); cursor.moveToNext(); } cursor.close(); sqLiteDatabase.close(); return colorsModelList; } public void deleteNote(int id){ SQLiteDatabase sqLiteDatabase = getWritableDatabase(); String whereclause = COLUMN_NAME + "='" + id + "';"; sqLiteDatabase.delete(TABLE_COLORS, whereclause, null); sqLiteDatabase.close(); } }
问题根源
- ColorsModel对象未携带ID:在
readNote方法中,读取到数据库的ID后,创建ColorsModel时只传入了名称,导致列表中的对象ID默认值为0。 - 删除条件错误:
deleteNote方法中错误地使用COLUMN_NAME作为匹配条件,而非COLUMN_ID,即使ID正确也无法匹配到对应数据。
修复步骤
1. 完善ColorsModel类
确保类中包含带ID和名称的构造方法,以及对应的Getter/Setter:
public class ColorsModel { private int id; private String name; public ColorsModel() {} public ColorsModel(String name) { this.name = name; } public ColorsModel(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
2. 修改readNote方法
在读取数据库数据时,传入ID创建ColorsModel对象:
public List<ColorsModel> readNote(){ List<ColorsModel> colorsModelList = new ArrayList<>(); SQLiteDatabase sqLiteDatabase = getReadableDatabase(); String query = "SELECT * FROM " + TABLE_COLORS + ";"; Cursor cursor = sqLiteDatabase.rawQuery(query, null); cursor.moveToFirst(); while (!cursor.isAfterLast()){ @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex(COLUMN_ID)); @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME)); // 传入ID和名称创建对象 colorsModelList.add(new ColorsModel(id, name)); cursor.moveToNext(); } cursor.close(); sqLiteDatabase.close(); return colorsModelList; }
3. 修复deleteNote方法
使用COLUMN_ID作为删除条件,同时用占位符避免SQL注入风险:
public void deleteNote(int id){ SQLiteDatabase sqLiteDatabase = getWritableDatabase(); String whereClause = COLUMN_ID + " = ?"; String[] whereArgs = {String.valueOf(id)}; sqLiteDatabase.delete(TABLE_COLORS, whereClause, whereArgs); sqLiteDatabase.close(); }
完成以上修改后,滑动列表项时就能正确获取到数据库中的ID,并通过ID实现精准删除。
内容的提问来源于stack exchange,提问作者Jason
相关产品推荐
相关产品推荐

