添加行插入光标手动 [英] Adding rows into Cursor manually
问题描述
我的电话号码数组,我想从联系人数据库中获取相应的联系人姓名。
I have an array of phone numbers and I want to get the corresponding contact names from the contacts database.
在电话号码数组,我也有未保存之前的联系人数据库的一些数字。例如;
In the array of phone numbers, I also have some numbers that are not saved before to the contact database. For example;
- 3333333 - >添
- 5555555 - >吉姆
- 1111111 - >未知
我上面显示包含电话号码的阵列,即的 phoneArr 的。
I have the array containing the phone numbers shown above, namely phoneArr.
int size=phoneArr.size();
if(size>0){
Cursor[] cursors=new Cursor[size];
for(int i=0;i<size;i++){
Uri contactUri1 = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneArr.get(i)));
cursors[i] = getContentResolver().query(contactUri1, PEOPLE_PROJECTION, null, null, " _id asc limit 1");
}
Cursor phones=new MergeCursor(cursors);
phones.getCount()在上述情况下返回2。当电话号码没有出现在联系人列表中的光标变成空的,不知怎的,当我把它们合并不利于在所有的事情。我要的是有一个光标如下:
phones.getCount() returns 2 in the above scenario. When the phone number does not appear in the contact list the cursor becomes empty and somehow when I merge them it doesn't contribute anything at all. What I want is to have a cursor as follows
光标手机 - > {添,吉姆,1111111}
我想我可以通过手动添加一行如下做到这一点:
I think I can do this by adding the row manually as follows:
Uri contactUri1 = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneArr.get(i)));
cursors[i] = getContentResolver().query(contactUri1, PEOPLE_PROJECTION, null, null, " _id asc limit 1");
if(cursors[i].getCount()==0)
// add the phone number manually to the cursor
我怎样才能做到这一点?
How can I achieve this?
下面是PEOPLE_PROJECTION
Here is the PEOPLE_PROJECTION
private static final String[] PEOPLE_PROJECTION = new String[] {
ContactsContract.PhoneLookup._ID,
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup.NUMBER
};
推荐答案
最容易在游标行添加的方法是使用一个 MatrixCursor 和 MergeCursor 。 这两个类是从SDK和这里解决那样的问题。
Easiest way to add rows in a cursor is to use a MatrixCursor and a MergeCursor. Those two classes are from the SDK and here to solve that kind of problems.
基本上,你做的是:
- 将要在
MatrixCusror
添加行
- 合并你的
光标
和您的matrixCursor
使用MergeCursor
- Put the rows you want to add in a
MatrixCusror
- Merge your
cursor
and yourmatrixCursor
using aMergeCursor
是这样的:
// Create a MatrixCursor filled with the rows you want to add.
MatrixCursor matrixCursor = new MatrixCursor(new String[] { colName1, colName2 });
matrixCursor.addRow(new Object[] { value1, value2 });
// Merge your existing cursor with the matrixCursor you created.
MergeCursor mergeCursor = new MergeCursor(new Cursor[] { matrixCursor, cursor });
// Use your the mergeCursor as you would use your cursor.
这篇关于添加行插入光标手动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!