我正在使用一个需要一些数据库操作的 android 应用程序,同样我使用下面的代码。我使用此代码的原因是因为我正在使用从表中提取的数据显示在 ListView 上,并且我需要删除一个随机列表 - 我可以在 ListView 和我的表之间找到的唯一关系是列表位置和索引值桌子。列表会自动更新,但表索引不会。
public void deleteValues(int position)
{
SQLiteDatabase db = this.getWritableDatabase();
position = position + 1;
String id = String.valueOf(position);
db.delete(FUEL_TABLE, KEY_ID + "="+id,null);
//Updating table
String CREATE_TABLE_COPY = "CREATE TABLE " + "COPIED_TABLE" + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_DATE + " TEXT,"
+ KEY_TIME + " TEXT," + KEY_PRICE + " TEXT," + KEY_AMOUNT + " TEXT," + KEY_FUELID + " INTEGER" + ")";
db.execSQL(CREATE_TABLE_COPY);
String db_insert_command;
db_insert_command = "INSERT INTO COPIED_TABLE (" + KEY_DATE +", " + KEY_TIME + ", " + KEY_PRICE + ", " + KEY_AMOUNT + ", " + KEY_FUELID + ") " +
"SELECT " + KEY_DATE +", " + KEY_TIME + ", " + KEY_PRICE + ", " + KEY_AMOUNT + ", " + KEY_FUELID + " FROM "+ FUEL_TABLE;
System.out.println(db_insert_command);
db.execSQL(db_insert_command);
db.execSQL("DROP TABLE " + FUEL_TABLE);
//Creating FUEL_TABLE again
String CREATE_TABLE = "CREATE TABLE " + FUEL_TABLE + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_DATE + " TEXT,"
+ KEY_TIME + " TEXT," + KEY_PRICE + " TEXT," + KEY_AMOUNT + " TEXT," + KEY_FUELID + " INTEGER" + ")";
db.execSQL(CREATE_TABLE);
db.execSQL("INSERT INTO " + FUEL_TABLE + " SELECT * FROM COPIED_TABLE");
db.execSQL("DROP TABLE COPIED_TABLE");
db.close();
}
我创建了这个函数来执行所有的数据库操作。这将创建一个新的临时表,并在随机删除过程之后复制原始表中的所有内容。(现在表的索引值可能是 1,2,3,5,6... 其中索引为 4 的行被删除。所以临时表将完美地创建具有升序索引的新行。然后这个临时表原表重新创建后复制到原表。
我的OnItemLongClickListener
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int pos, long id) {
// TODO Auto-generated method stub
alert.setTitle("Fuel Calculator");
// set dialog message
alert
.setMessage("Delete this entry?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
db.deleteValues(pos);
System.out.println("Performing delete from DB and populating Listsview again");
Intent i = new Intent(getApplicationContext(), ListviewActivity.class);
startActivity(i);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
我的适配器
ListAdapter adapter = new SimpleAdapter(this, Items,
R.layout.list_item,new String[] { "date","time", "amount", "price" },
new int[] {R.id.date, R.id.time, R.id.price, R.id.capacity });
setListAdapter(adapter);
我认为这个逻辑和代码是垃圾。我认为有更好的方法可以做到这一点。请帮忙