may i ask for help…i manage to add data to database..but i got problem to delete the data..because i can’t delete based on ID from my ListView…how to get the ID??..this is my code..
This class name as ViewActivity.java where i display my database content…i only display one column only in my ListView
String query = "select * from " + helper.TABLE_PEKERJA;
Cursor c = database.rawQuery(query, null);
if(c!=null)
{
c.moveToFirst();
int getNamaIndex = c.getColumnIndex(helper.COL_NAMA);
if(c.isFirst())
{
do{
String nama = c.getString(getNamaIndex);
result.add(nama);
}while(c.moveToNext());
}
}
this.setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,result));
getListView().setTextFilterEnabled(true);
in my DBHelper, i create a method for delete row from my database table which is here..
public void deleteData(SQLiteDatabase db, String id)
{
db.delete(TABLE_PEKERJA, COL_ID + " = " +id, null);
}
then still in the class ViewActivity.java, i implement method onListItemClick
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
DBHelper helper = new DBHelper(this);
database = helper.getWritableDatabase();
Object o = this.getListAdapter().getItem(position);
String keyword = o.toString();
helper.deleteData(database, keyword);
Toast.makeText(this, "Data " + keyword + " removed" , Toast.LENGTH_SHORT).show();
}
also got this error..this error only i can view…this error at part
Object o = this.getListAdapter().getItem(position);
02-09 02:34:23.729: E/Database(28923): at com.example.untukmuna.ViewContentActivity.onListItemClick(ViewContentActivity.java:69)
So, my question is
1) How do i delete my database table row, when i press item in ListView based from ID
2) when creating database, there has db.open()…but where should i close database buy putting db.close() …??
thanksss~~ hope you all understand my question.. ^_^
the way that it is conventionally done is that you simply get the
idfrom the list click parameter.But you can’t immediately do this because your
ListViewis hooked up to anArrayAdapterand not aCursorAdapter. Right now, thatidwill either always be 0 or some non-sense value. I would recommend that you change your adapters if you need to do tasks like this.But if you need your adapters as is, then what you could do is make a corresponding
idcollection of some sort that you fill as you loop through your database to fillresult. Then it would be as simple as getting thepositionfrom theonListItemClickparameter then getting theidfrom the id collection.you’d of course, have to make sure that you’re deleting the value off this collection as you’re deleting the row of the listview.
try the following: