I want to delete a particular row from the listview, in which the data is being populated from the database. On setOnItemLongClickListener
I have been able to delete the data from the listview, but when I restart my activity I can see that the row which I have deleted is there because on onCreate()
I fetch the data from the database.
Here what I have done:
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;
}
});
My delete method in 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();
}
My delete query in AndroidOpenDbHelper.java
public boolean deleteTitle(long rowId) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME_HISTORY, ID + "=" + rowId, null) > 0;
}
Again, I'm able to delete the data from the listview but not from the database. Please help me in overcoming this problem.
first ur get all row id's using following code
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();
}
on listview item click
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) {
}
}