11

I'm new to Android. I'm searching for load photo to facebook by authorization, getting access_token. How to do this? Please give me a sample code in Java.

halfer
  • 19,824
  • 17
  • 99
  • 186
sanjana
  • 119
  • 1
  • 1
  • 3

5 Answers5

15

Just posted here the simple way to upload a photo:

android facebook publish photo

Code:

byte[] data = null;

Bitmap bi = BitmapFactory.decodeFile(photoToPost);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();

Bundle params = new Bundle();
params.putString("method", "photos.upload");
params.putByteArray("picture", data);

AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
Community
  • 1
  • 1
Anthony Graglia
  • 5,355
  • 5
  • 46
  • 75
8
facebook.authorize(FbdemoActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener() {
                    @Override
                    public void onComplete(Bundle values) {



                    }

                    @Override
                    public void onFacebookError(FacebookError error) {
                    }

                    @Override
                    public void onError(DialogError e) {
                    }

                    @Override
                    public void onCancel() {
                    }
                });


public void postImageonWall() {

           byte[] data = null;

             Bitmap bi = BitmapFactory.decodeFile("/sdcard/viewitems.png");
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
             bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
             data = baos.toByteArray();


             Bundle params = new Bundle();
             params.putString(Facebook.TOKEN, facebook.getAccessToken());
             params.putString("method", "photos.upload");
             params.putByteArray("picture", data);

             AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
             mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);


    }


public class SampleUploadListener extends BaseRequestListener {

    public void onComplete(final String response, final Object state) {
        try {
            // process the response here: (executed in background thread)
            Log.d("Facebook-Example", "Response: " + response.toString());
            JSONObject json = Util.parseJson(response);
            final String src = json.getString("src");

            // then post the processed result back to the UI thread
            // if we do not do this, an runtime exception will be generated
            // e.g. "CalledFromWrongThreadException: Only the original
            // thread that created a view hierarchy can touch its views."

        } catch (JSONException e) {
            Log.w("Facebook-Example", "JSON Error in response");
        } catch (FacebookError e) {
            Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
        }
    }

    @Override
    public void onFacebookError(FacebookError e, Object state) {
        // TODO Auto-generated method stub

    }
}

here is the whole code try it it will definately work for you and it is work for me also

Nilesh Gawade
  • 237
  • 4
  • 3
  • 1
    What is BaseRequestListener ? – Shreyash Mahajan Nov 09 '11 at 11:13
  • Your example works for me. But in extra i want to post the simple message with that photo post. So how it is possible ? Any idea ? give answer here.: http://stackoverflow.com/questions/8585043/android-how-to-post-the-message-with-the-image-post-on-facebook – Shreyash Mahajan Dec 21 '11 at 04:41
  • photos.upload isn't a deprecated Legacy Rest Api method? – Cassio Landim May 17 '12 at 14:37
  • 1
    This code does work with the following caveats. 1. I put the facebook.authorize() call inside an onClick(). I added the other 2 methods to my existing Activity. 2. It results in an out of memory error if you repeat the upload more than once per application run. – Bill Mote Jul 04 '12 at 14:24
  • 1
    android not recognizing the BaseRequestListener. Where this class exist? I need a complete code. I dont know where facebook object come from? e.g facebook.authorize() – Muhammad Aamir Ali Dec 23 '12 at 15:25
  • how to share more the one image to facebook – jyomin Nov 12 '14 at 09:07
  • @MuhammadAamirAli same problem! Cannot resolve symbol 'BaseRequestListener' – Srichakradhar Dec 10 '15 at 18:48
4

The easiest way for you is to use the existing SDK, something like that:
http://github.com/facebook/facebook-android-sdk/
http://code.google.com/p/fbconnect-android/
http://wiki.developers.facebook.com/index.php/User:Android

The more flexible way is to implement the API yourself, here are the docs that will be useful:
http://developers.facebook.com/docs/

Fedor
  • 43,261
  • 10
  • 79
  • 89
  • 2
    Looking at the FB api, I don't see any way to upload an image. I only see that you can pass an image URL as a parameter, but not the image data itself. Or have I overlooked anything? – Mathias Conradt Jan 05 '11 at 16:27
  • how to share more than one image to fb..please help – jyomin Nov 12 '14 at 09:09
3

If you want to publish a photo with a description you can do this :

public void publishPhoto(byte[] imgData, string message) {

AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner (facebook);

Bundle parameters = new Bundle ();
parameters.putString (Facebook.TOKEN, facebook.getAccessToken());
parameters.putString ("message", message);
parameters.putByteArray ("source", imgData);

mAsyncRunner.Request ("me/photos", parameters, "POST", new RequestListener (), null);
}
  • 1
    +1 That's it! Thank you. After sifting through so many people using the legacy api, this one is finally showing the Graph api solution. – Lee Oades Oct 15 '12 at 21:23
3

Successfully i have uploaded the photos on facebook wall I used the following code.

In your Main Activity do the following;

btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            authenticatedFacebook.authorize(Facebooktest2Activity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener() {
                    @Override
                    public void onComplete(Bundle values) {
                        postImage();
                        Toast.makeText(getApplicationContext(), "Image Posted on Facebook.", Toast.LENGTH_SHORT).show();


                    }

                    @Override
                    public void onFacebookError(FacebookError error) {
                    }

                    @Override
                    public void onError(DialogError e) {
                    }

                    @Override
                    public void onCancel() {
                    }

    });


        }
});






}

public void postImage(){
     byte[] data = null;               

        Bitmap bi = BitmapFactory.decodeFile("/sdcard/img.jpg");
        //Bitmap bi = BitmapFactory.decodeResource(getResources(), R.drawable.icon);             
        ByteArrayOutputStream baos = new ByteArrayOutputStream();              
        bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);              
        data = baos.toByteArray();                
        Bundle params = new Bundle();              
        params.putString(Facebook.TOKEN, authenticatedFacebook.getAccessToken());              
        params.putString("method", "photos.upload");              
        params.putByteArray("picture", data);               
        AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(authenticatedFacebook);              
        mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);   

}


public class SampleUploadListener extends BaseKeyListener implements RequestListener {

    public void onComplete(final String response, final Object state) {
        try {
            // process the response here: (executed in background thread)
            Log.d("Facebook-Example", "Response: " + response.toString());
            JSONObject json = Util.parseJson(response);
            final String src = json.getString("src");

            // then post the processed result back to the UI thread
            // if we do not do this, an runtime exception will be generated
            // e.g. "CalledFromWrongThreadException: Only the original
            // thread that created a view hierarchy can touch its views."

        } catch (JSONException e) {
            Log.w("Facebook-Example", "JSON Error in response");
        } catch (FacebookError e) {
            Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
        }
    }

    public void onFacebookError(FacebookError e, Object state) {
        // TODO Auto-generated method stub

    }

    public Bitmap getInputType(Bitmap img) {
        // TODO Auto-generated method stub
        return img;
    }

    @Override
    public int getInputType() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void onIOException(IOException e, Object state) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onFileNotFoundException(FileNotFoundException e,
            Object state) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onMalformedURLException(MalformedURLException e,
            Object state) {
        // TODO Auto-generated method stub

    }
}

Surely This code will help you.

ahsteele
  • 26,243
  • 28
  • 134
  • 248
vennila
  • 41
  • 4
  • I used this code, and got exception as java.lang.OutOfMemoryError at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:103) at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:234) at android.graphics.Bitmap.nativeCompress(Native Method) in this line bi.compress(Bitmap.CompressFormat.JPEG, 100, baos); – Manikandan Jun 07 '12 at 10:08
  • authenticatedFacebook is what..it gives mee an error..please help – jyomin Mar 03 '14 at 11:17
  • what if we have to share more then one image to facebook..please help – jyomin Nov 12 '14 at 09:05