ContentProvider 的 delete 可刪除資料,並且該方法返回當前刪除資料的記錄個數。
sdk api 描述
但是,看完下面的內容,你就會發現,情況不是表面上那樣的!
現有資料庫表內容如下
1. 在 android2.1 的模擬器上面
通過下面語句刪除 _id=1 的記錄
[java]
final int delRows = getContentResolver().delete(
UserTableData.CONTENT_URI, "_id=1", null);
Log.d("mark", "delete data and delRows = " + delRows);
傳回值資訊
如果刪除資料庫中表的所有資料,可以這樣
[java]
@Override
public void onClick(View v) {
final int delRows = getContentResolver().delete(
UserTableData.CONTENT_URI, null, null);
Log.d("mark", "delete data and delRows = " + delRows);
}
傳回值資訊
兩者返回的資訊,都是正確的!
2. 在 android2.1 的真機上面
把同樣的程式運行在真機上,刪除某條記錄,返回結果都是:
而刪除所有資料,返回結果卻是
與實際情況不符合。
當初還以為,刪除失敗,但是開啟資料庫看看,裡面的確是沒有資料了?!
奇怪的、詭異的現象,為什嗎?
3. 解決問題
通過 ContentProvider 來刪除資料,其實是調用 SQLiteDatabase 的 delete 方法
android sdk api 中 SQLiteDatabase 的 delete 方法
仔細研究一下,發現 To remove all rows and get a count pass "1" as the whereClause.
於是代碼修改
[html]
final int delRows = getContentResolver().delete(
UserTableData.CONTENT_URI, "1", null);
Log.d("mark", "delete data and delRows = " + delRows);
再次,測試代碼,真機和模擬器都返回了正確的結果!
問題解決!