Tuesday, 5 March 2013

Facebook Android SDK 3.0 - getting a user's profile picture

Here's another Facebook operation which you'd think should not only be easy to do but also be easy to find in the documentation. It certainly was easy to do, but once again wasn't so easy to find in the documentation. Oh and, strictly speaking, you don't need the Facebook SDK for this. You just need to make a HTTP GET call to the Facebook user's picture connection. (You'll need the Facebook SDK to get the user's Facebook id beforehand.)

final String userFacebookId = ...

new AsyncTask<Void, Void, Bitmap>()
{
  @Override
  protected Bitmap doInBackground(Void... params)
  {
    // safety check
    if (userFacebookId == null)
      return null;

    String url = String.format(
        "https://graph.facebook.com/%s/picture",
        userFacebookId);

    // you'll need to wrap the two method calls
    // which follow in try-catch-finally blocks
    // and remember to close your input stream

    InputStream inputStream = new URL(url).openStream();
    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

    return bitmap;
  }

  @Override
  protected void onPostExecute(Bitmap bitmap)
  {
    // safety check
    if (bitmap != null
        && !isChangingConfigurations()
        && !isFinishing())
      // do what you need to do with the bitmap :)
  }
}.execute();

3 comments:

Anonymous said...

Thanks for the help!

Anonymous said...

it returns null by the way. the url is redirected.

Naren Thapa said...

Much helpful for me and did little improvise in this code.

String userFacebookId ="";

if (userFacebookId == null)
return null;

String url = String.format("https://graph.facebook.com/%s/picture",userFacebookId);

// you'll need to wrap the two method calls
// which follow in try-catch-finally blocks
// and remember to close your input stream

InputStream inputStream = null;
try {
inputStream = new URL(url).openStream();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

img.setImageBitmap(bitmap);