java Android - 如何从光标中删除项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6724714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:01:44  来源:igfitidea点击:

Android - how to delete item from a cursor?

javaandroidcursor

提问by JDS

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.

现在我将如何删除该游标中的第 i 个项目?这也可能是获取音乐列表等的光标。所以我必须问 - 这甚至可能吗?我可以理解某些游标不允许 3rd 方应用程序从中删除。

Thanks.

谢谢。

回答by MikeWallaceDev

Sorry mate you can't delete from a cursor.

抱歉,您无法从光标中删除。

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

您必须使用 ContentResolver 或某种 SQL 调用。

回答by Glenn Bech

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.

您可以使用 MatrixCursor 来解决问题。使用此策略,您可以复制游标,并省略要排除的一行。这 - 显然,对于大型游标不是很有效,因为您会将整个数据集保存在内存中。

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

您还必须在 MatrixCursor 的构造函数中重复列名的 String 数组。你应该把它作为一个常量。

   //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 ... :-)

我不断地与这个斗争;尝试仅使用游标和内容提供程序制作我的应用程序,尽可能远离对象映射。你应该看到我的一些 ViewBinders ... :-)