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 -> Tim
- 5555555 -> Jim
- 1111111 -> unknown
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() 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
Cursor phones -> {Tim, Jim, 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?
Here is the PEOPLE_PROJECTION
private static final String[] PEOPLE_PROJECTION = new String[] {
ContactsContract.PhoneLookup._ID,
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup.NUMBER
};
I know this an old post, but it is a real pain that rows can not be added manually to a Cursor. I have come up with a crude solution. It might be of some help.
Cursor
is actually aninterface
and you can create a customclass
thatimplements
theCursor
interface.And finally in your code
That should do it. But be warned though, for this to work, you have to be wise while implementing the
Cursor
interface.Unfortunately, As far as I know, there is no way that you can manually add data to the cursor. You need to handle this in a different way.
The only way that I can think of in which you can do this is
cursoradapter
implementation to anarrayadapter
.I use a solution that does the trick for all my different needs, and which is simpler than implementing Cursor.
Here is an example where I have to add extra "playlist" rows to a Cursor, retrieved from the Mediastore. I add rows at first indexes of the original Cursor :
Original cursor has 2 columns (int,String), so I construct it with an array of extra rows objects.
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.
Basically what you do is :
MatrixCusror
cursor
and yourmatrixCursor
using aMergeCursor
Something like: