Uploading a Photo with the Facebook Android SDK

Facebook’s example code for Android shows how to upload a photo using the REST API rather than the newer Graph API. I knew that the iOS SDK can handle it via Graph just fine, so I changed the code in my Android app to use Graph as well (also since doing it with REST wasn’t working). I’ve added a quick method for uploading a picture below, hopefully it works since it was modified from the original and thus untested. It runs synchronously, so you will want to run this in a separate thread (or else convert it to the Async API – in my app it was just easier to make it multithreaded).

public static String uploadPhoto(Facebook facebook, Bitmap image,
        String albumId)
{
    if ( albumId == null ) {
        albumId = "me";
    }

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    image.compress(CompressFormat.JPEG, 75, bos);
    byte[] photoBytes = bos.toByteArray();

    Bundle params = new Bundle();
    params.putByteArray("picture", photoBytes);

    try {
        String resp = facebook.request(albumId + "/photos", params, "POST");
        JSONObject json = Util.parseJson(resp);
		return json.getString("id");
    } catch ( IOException e ) {
    } catch ( FacebookError e ) {
    } catch ( JSONException e ) {
    }

    return null;
}
This entry was posted in Java and tagged , . Bookmark the permalink.

2 Responses to Uploading a Photo with the Facebook Android SDK

  1. Andrés says:

    It is not working for my, I am trying with different codes but I can´t, could you send me a little project with the minimal classes required to upload a picture to facebook?

    Thanks in advance,
    Andrés.

  2. sarvanjaimin says:

    How to implement Uploading a Photo with the flicker Android SDK….

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>