Search code examples
androidcontactsgoogle-account

Get main account photo


I am creating an app and I have a photo for the user and I would like to automatically pull it. I am not really sure how to do this or what would even be the best way to do this.

Is there a way to pull the google account photo? This might not even be the best way to go considering that plenty of people world wide may not have a google account at all.

Is there a default contact for the user of the phone in the ContactProvider and if so how would I go about getting it and the photo it has. Sorry I don't have any code, I just don't know where to start and a suggestion or a link might point me in the right direction.

Okay code that I tried

String[] mProjection = new String[]
            {
            Profile._ID,
            Profile.DISPLAY_NAME_PRIMARY,
            Profile.LOOKUP_KEY,
            Profile.PHOTO_THUMBNAIL_URI
            };

    // Retrieves the profile from the Contacts Provider
    Cursor mProfileCursor = mContext.getContentResolver().query(
            Profile.CONTENT_URI,
            mProjection ,
            null,
            null,
            null);

    try {
         if (mProfileCursor.moveToFirst()) {
             byte[] data = mProfileCursor.getBlob(0); //error on this line
             if (data != null) {
                 InputStream is = new ByteArrayInputStream(data);
                 imageBit = BitmapFactory.decodeStream(is);
             }
         }
     } finally {
         mProfileCursor.close();
     }

I keep getting an error on the noted line:

android.database.sqlite.SQLiteException: unknown error (code 0): INTEGER data in nativeGetBlob

Edit 2: so I changed the 0 to a 3 to get the profile photo it fixed my one error but now the imageBit that I get from decoding the stream is null. The byte[] however is not so I don't know what the issue is converting the byte[] to an bitmap


Solution

  • Inside ContactsContract.Contacts you can found a row dedicated to the Phone owner.

    Remember to add READ_PROFILE permission to your application.

    // Sets the columns to retrieve for the user profile
    mProjection = new String[]
        {
            Profile.PHOTO_THUMBNAIL_URI
        };
    
    // Retrieves the profile from the Contacts Provider
    mProfileCursor =
            getContentResolver().query(
                    Profile.CONTENT_URI,
                    mProjection ,
                    null,
                    null,
                    null);
    

    Then use mProfileCursor to get the data and show it.

    More info, here.