Android changing contact's photo
<p>I'm  trying to change contact's photo by using this code: </p>

<pre><code>public void setContactPhoto(byte[] bytes, long personId) {
    ContentResolver cr = getContentResolver();
    ContentValues values = new ContentValues();
    int photoRow = -1;
    String where = ContactsContract.Data.RAW_CONTACT_ID + " = " + personId
            + " AND " + ContactsContract.Data.MIMETYPE + "==' "
            + Photo.CONTENT_ITEM_TYPE
            + "'";
    Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI, null, where,
            null, null);
    int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID);

    if (cursor.moveToFirst()) {
        int i=1;
        photoRow = cursor.getInt(idIdx);
        while (cursor.moveToNext()){
            photoRow = cursor.getInt(idIdx);            

            i++;
        }
    } else {

    }
    cursor.close();
    try {

        values.put(ContactsContract.Data.RAW_CONTACT_ID, personId);
        values.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
        values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes);
        values.put(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);

        if (photoRow &gt;= 0) {
            cr.update(ContactsContract.Data.CONTENT_URI, values,
                    ContactsContract.Data._ID + " = " + photoRow, null);


        } else {
            cr.insert(ContactsContract.Data.CONTENT_URI, values);

        }
    } catch (Exception e) {

    }

}
</code></pre>

<p>For most contacts it's work fine, but for other I have a problem. 
When I tried to debug it, I noticed for some things: </p>

<ol>
<li><p>For some contacts the query return -1 (when for other it's return  photoRow>0 even I'm not set their photo before ) </p></li>
<li><p>When the query return -1 and I'm using to insert new row I cant see  the photo in the contacts list </p></li>
<li><p>Sometimes I get photoRow>0 but not belong to the contact I tried to update it's photo</p></li>
<li><p>Sometimes I get more than one result so  I can't know which one of them I need in order to update the contact photo </p></li>
</ol>

<p>Can anybody help me how to deal with this problem? 
I thought that the query should return me a specific row which belong 
to a specific contact. </p>
