当我尝试使用删除方法删除数据库中的一行时,我的 android 代码出现问题。但是,我不想使用 ID,而是使用我创建的字符串的名称。重点是用户在编辑文本中输入名称并删除字符串行。我对此很陌生,希望您能提供意见!我会带你看我的代码...
这是我的数据
public class Key_Manager extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String CREATE_KEYS_TABLE = "CREATE TABLE " + KeyEntry.TABLE_NAME +
" (" +
KeyEntry.KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
KeyEntry.COLUMN_NAME_NAME + " TEXT," +
KeyEntry.COLUMN_NAME_KEY + " TEXT" + ")";
public Key_Manager(Context context)
{
super(context,KeyEntry.DB_NAME, null, DATABASE_VERSION );
}
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(CREATE_KEYS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS" + KeyEntry.TABLE_NAME);
onCreate(db);
}
public void addKey(String name, String key)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KeyEntry.COLUMN_NAME_NAME, name);
values.put(KeyEntry.COLUMN_NAME_KEY, key);
try{db.insertOrThrow(KeyEntry.TABLE_NAME, null, values);}
catch(Exception e)
{
Log.e("Error in inserting rows", e.toString());
e.printStackTrace();
}
db.close();
}
public ArrayList<String> getKeys(int id)
{
ArrayList<String> listRows = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
String[] keys = new String[]
{
KeyEntry.KEY_ID, KeyEntry.COLUMN_NAME_NAME,
KeyEntry.COLUMN_NAME_KEY };
Cursor cursor = db.query(KeyEntry.TABLE_KEY, keys, KeyEntry.KEY_ID + "=?", null, null, null, null);
if(cursor !=null)
{
cursor.moveToFirst();
}
while(cursor.isAfterLast()==false)
{
listRows.add(cursor.getString(0));
listRows.add(cursor.getString(1));
cursor.moveToNext();
}
if(cursor != null && !cursor.isClosed())
{
cursor.close();
}
return listRows;
}
public void onDownGrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
onUpgrade(db, oldVersion, newVersion);
}
public void deleteKey(String name) //THIS IS WHERE I AM HAVING PROBLEMS, WHAT SHOULD I DO HERE?
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(KeyEntry.TABLE_NAME, KeyEntry.COLUMN_NAME_NAME,new String[]{name});
}
}
这是我要删除它的地方
public class Delete_Keys extends Activity {
private Key_Manager keyManager;
EditText delete;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete__keys);
delete = (EditText) findViewById(R.id.enterDelete);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.delete__keys, menu);
return true;
}
public void deleteButton(View v)//AM I DOING THIS CORRECT? WHAT CAN I DO BETTER?
{
String name = delete.getText().toString();
keyManager = new Key_Manager(this);
keyManager.deleteKey(name);
}
}