Android - how to delete item from a cursor?

冷暖自知 提交于 2019-12-01 06:47:25

问题


Let's say I make the following cursor to get the call log of someone:

String[] strFields = {
    android.provider.CallLog.Calls.NUMBER, 
    android.provider.CallLog.Calls.TYPE,
    android.provider.CallLog.Calls.CACHED_NAME,
    android.provider.CallLog.Calls.CACHED_NUMBER_TYPE
    };

String strOrder = android.provider.CallLog.Calls.DATE + " DESC"; 

Cursor mCallCursor = getContentResolver().query(
        android.provider.CallLog.Calls.CONTENT_URI,
        strFields,
        null,
        null,
        strOrder
        );

Now how would I go about deleted the ith item in this cursor? This could also be a cursor getting list of music, etc. So then I must ask - is this even possible? I can understand for certain cursors that 3rd party apps wouldn't be allowed to delete from.

Thanks.


回答1:


Sorry mate you can't delete from a cursor.

You must either use your ContentResolver or a SQL call of some sort..




回答2:


You can to a trick with a MatrixCursor. With this strategy, you copy the cursor, and leave out the one row you want to exclude. This is - obviously, not very efficient for large cursors as you will keep the entire dataset in memory.

You also have to repeat the String array of column names in the constructor of the MatrixCursor. You should keep this as a Constant.

   //TODO: put the value you want to exclude
   String exclueRef = "Some id to exclude for the new";
   MatrixCursor newCursor = new MatrixCursor(new String[] {"column A", "column B");
         if (cursor.moveToFirst()) {
            do {
                // skip the copy of this one .... 
                if (cursor.getString(0).equals(exclueRef))
                    continue;
                newCursor.addRow(new Object[]{cursor.getString(0), cursor.getString(1)});
            } while (cursor.moveToNext());
        }

I constantly battle with this; trying to make my apps with cursors and content providers only, keeping away from object mapping as long as I can. You should see some of my ViewBinders ... :-)



来源:https://stackoverflow.com/questions/6724714/android-how-to-delete-item-from-a-cursor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!