我想从列表视图中删除特定行,其中从数据库中填充数据。在setOnItemLongClickListener
我已经能够从列表视图中删除数据,但是当我重新启动我的活动时,我可以看到我删除的那行是因为在onCreate()
我从数据库中获取数据
这就是我所做的:
MainActivity.java
db = new AndroidOpenDbHelper(this);
showing_history
.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0,
View arg1, final int pos, final long id) {
final AlertDialog.Builder b = new AlertDialog.Builder(
MainActivity.this);
b.setIcon(android.R.drawable.ic_dialog_alert);
b.setMessage("Delete this from history?");
b.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
HistoryNamesList.remove(pos);
((BaseAdapter) mHistoryListAdapter)
.notifyDataSetChanged();
del(pos);
}
});
b.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
dialog.cancel();
}
});
b.show();
return true;
}
});
我在MainActivity.java中的删除方法:
private void del(int j) {
if (db.deleteTitle(j))
Toast.makeText(this, "Delete successful.", Toast.LENGTH_LONG)
.show();
else
Toast.makeText(this, "Delete failed.", Toast.LENGTH_LONG).show();
db.close();
}
我在AndroidOpenDbHelper.java中的删除查询
public boolean deleteTitle(long rowId) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME_HISTORY, ID + "=" + rowId, null) > 0;
}
同样,我可以从列表视图中删除数据,但不能从数据库中删除。请帮我克服这个问题。
答案 0 :(得分:1)
首先使用以下代码获取所有行ID
private int[] mRowId;
dba.open();
Cursor cr=dba.fetchData();
cr.moveToFirst();
int i=0;
while(!cr.isAfterLast())
{
mRowId[i]==cr.getInt(cr.getColumnIndex("colname"));
i++;
cr.moveToNext();
}
列表视图项目上的单击
list.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
db.deleteTitle(mRowId[pos]);
return true;
}
public void deleteTitle(int rowid) {
try {
database.execSQL("DELETE FROM TableName" + " where columnname="
+ rowid + ";");
} catch (Exception e) {
}
}
答案 1 :(得分:0)
尝试使用db.raw查询而不是db.delete ...我希望这可以帮助你..
答案 2 :(得分:0)
试试这段代码
public void deleteTableRow(int rowid) {
try {
database.execSQL("DELETE FROM TableName" + " where columnname="
+ rowid + ";");
} catch (Exception e) {
}
}