sqlite delete last row refresh not working
I have a long press option on my listview which will delete the long pressed db entry. The delete does actually work. If i come out of the app and go back in i am presented with my 'no rows' message. Perfect.
In my code I first call the DBadapter method to delete a row. I then call a fetchallnotes method in the dbadapter to refresh my listview. The last row won't disappear, however, on this fetchallnotes call.. Only on the fetchallnotes call in my onCreate.
Here is my Context Menu call which calls my DBAdapter method
db.deleteNote(info.id);
getSnapz();
This my my deleteNote method in DBAdapter
public boolean deleteNote(long rowId) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
here is my getSnapz method, which is in my Main activity which is where my listview is
public void getSnapz(){
try {
Cursor c = db.fetchAllNotes();
//requery cursor incase the last entry has been deleted
c.requery();
startManagingCursor(c);
if(c.moveToFirst()){
String[] from = new String[]{DBAdapter.KEY_TYPE,DBAdapter.KEY_WEIGHT,DBAdapter.KEY_DATE,DBAdapter.KEY_PLACE};
int[] to = new int[]{R.id.typecol,R.id.weightcol,R.id.datecol,R.id.placecol};
SimpleCursorAdapter simple = new SimpleCursorAdapter(this, R.layout.snapz_row, c, from, to);
setListAdapter(simple);
}
} catch (Exception e) {
Log.e(TAG,e.toString());
}
}
And here is my fetchAllNotes method in DBAdapter
public Cursor fetchAllNotes() throws Exception{
Cursor c = db.query(DATABASE_TA开发者_运维知识库BLE, new String[] {KEY_ROWID,KEY_URI, KEY_DATE,KEY_TYPE,KEY_WEIGHT,
KEY_PLACE},
null, null, null, null, null );
return c;
}
After you delete the last row, the cursor returned is empty. Therefore c.moveToFirst() returns false, your whole if block is skipped, and your listview is left unchanged, still showing the just-deleted row.
It works when you delete one of several rows because moveToFirst() returns success as long as there was another row still left.
It works when you exit and resume because at that point the activity is recreated and the listview starts uninitialized.
Solution: drop the if statement completely. SimpleCursorAdapter should be happy with a cursor with 0 rows.
Long term better yet, migrate to a ContentProvider and use the ContentObserver model to make sure your cursors update themselves when the database they reflect changes.
精彩评论