Upload photo to Facebook page in a specific album - android

I am busy with uploading a photo to Facebook. The requirement is that we need to upload the photo on a specific album on a page. This is the link to the page : https://business.facebook.com/manegedagen/.
I can successfully upload a photo to the timeline but my requirement is to upload the photo in an album. So below i first start with getting all albums from a specific page.
public void getAlbum() {
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/2091172661108128/albums",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
pageAlbums = new Gson().fromJson(response.getRawResponse(), FacebookResponseAlbum.class);
postImageOnWall(bitmap);
Log.e("", "");
}
}
).executeAsync();
}
In this case this 2091172661108128 is the id of the page for which i am getting a list of albums.
So later i am trying to post a picture on a specific album
public void postImageOnWall(Bitmap pBitmap) {
Album dttAlbum = getDttAlbum(pageAlbums);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
pBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
String a = String.valueOf( dttAlbum.getId() ).concat("/photos");
byte[] byteArray = byteArrayOutputStream.toByteArray();
Bundle bundle = new Bundle();
bundle.putByteArray("object_attachment", byteArray);// object attachment must be either byteArray or bitmap image
bundle.putString("message", "hey fibs it works");
new GraphRequest(AccessToken.getCurrentAccessToken(),
String.valueOf( dttAlbum.getId() ).concat("/photos") ,
bundle,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.e("", "");
}
}
).executeAsync();
}
The problem is that i am getting : {Response: responseCode: 400, graphObject: null, error: {HttpStatus: 400, errorCode: 200, errorType: OAuthException, errorMessage: Permissions error}} as response.
Any help will be appreciated.

Related

Post an image to facebook failed in android using facebook SDk 4.0

I am working on an android app and want to share an image to facebook from my app but without showing dialog,I have tried as below,But its not working .Can anybody help me for this?
code
public void postFb(){ String path = "me/feed";
AccessToken at = AccessToken.getCurrentAccessToken();
Bundle parameters = new Bundle();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Const.bmp_post.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
parameters.putByteArray("picture", byteArray);
HttpMethod method = HttpMethod.POST;
GraphRequest.Callback cb = new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse graphResponse) {
Log.d("=======graph response=======" , graphResponse.toString());
//check graphResponse for success or failure
if(graphResponse.getError()==null){
Toast.makeText(NewPostActivity.this, "Successfully posted to Facebook", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(NewPostActivity.this, "Facebook: There was an error, Please Try Again", Toast.LENGTH_SHORT).show();
}
}
};
GraphRequest request = new GraphRequest(at,path,parameters,method,cb);
request.setParameters(parameters);
request.executeAsync();
}
Try changing "/me/feed" to "me/photos"

Android - Get profile cover picture from Facebook

I am using Facebook SDK and Parse SDK and I want to retrieve the profile cover picture.
I am doing the following:
new Request(
ParseFacebookUtils.getSession(),
"/me?fields=cover",
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
Log.wtf("TAG",
response.toString());
}
}).executeAsync();
But I am not able to get the proper response since it says I need an access token (the user has already been logged in).
{Response:
responseCode: 400,
graphObject: null,
error: {
HttpStatus: 400,
errorCode: 2500,
errorType: OAuthException,
errorMessage: An active access token must be used to query information about the current user.
},
isFromCache:false
}
Is there any fix for this available?
After spending A LOT of hours searching for the answer, I finally got it !!!
The Android SDK for Facebook docs, are too useless.
To solve this problem we just need to set the Graph Path in the second param and a Bundle with fields as third param. Example:
Bundle params = new Bundle();
params.putString("fields", "cover");
new Request(ParseFacebookUtils.getSession(),
"me",
params,
HttpMethod.GET,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
//code...
}
}).executeAsync();
Then we can parse the response object returned in onCompleted as JSON with
response.getGraphObject().getInnerJsonObject();
//or
response.getGraphObject().getProperty("cover");
Source: New Facebook SDK and OAuthException in Graphpath requests thanks to #Jesse Chen
Facebook changed a few things and has some terrible documentation. Hope this helps someone else it's what worked for me.
public void getCoverPhotoFB(final String email, AccessToken accessToken){
if(!AccessToken.getCurrentAccessToken().getPermissions().contains("user_photos")) {
Log.e(L, "getCoverPhotoFB....get user_photo permission");
LoginManager.getInstance().logInWithReadPermissions(
this,
Arrays.asList("user_photos"));
}
////
Bundle params = new Bundle();
params.putBoolean("redirect", false);
params.putString("fields", "cover");
new GraphRequest(
accessToken,
"me",
params,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(final GraphResponse response) {
Log.e(L, "getCoverPhotoFB..."+response);
// thread is necessary for network call
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
String picUrlString = (String) response.getJSONObject().getJSONObject("cover").get("source");
Log.d(L,"getCoverPhotoFB.....picURLString....."+picUrlString);
URL img_value = new URL(picUrlString);
Bitmap eventBitmap = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
saveImageToExternalStorage(eventBitmap, email + "_B.png");
homeProfile(profile, email);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
thread.start();
}
}
).executeAsync();
}

Android - Facebook API : post image

I'm building an app that allows Facebook users to create new events. I noticed that I can't create an event and add an image to it in a unique Graph API call. So I make another call to post the image:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
Bundle params = new Bundle();
params.putParcelable("source", bitmap);
Request postImageRequest = new Request(Session.getActiveSession(), eventId + "/picture", params, HttpMethod.POST, new Callback() {
#Override
public void onCompleted(Response response) {
Log.e("", response.toString());
finish();
}
});
postImageRequest.executeAsync();
But but I get this error response from FB servers:
HttpStatus: 400, errorCode: 324, errorType: OAuthException,
errorMessage: (#324) Missing or invalid image file}, isFromCache:false
Request photoImageRequest= Request.newUploadPhotoRequest(Session.getActiveSession(), bitmap, new Request.Callback(){
#Override
public void onCompleted(Response response) {
Log.e("", response.toString());
finish();
}});

New Facebook SDK and OAuthException in Graphpath requests

I saw a buch of answers regarding this problem with the older versions of the SDK, and I can't seem figure out why this is happening to me.
if I use this code, it works perfectly:
String QUERY = "select uid, name, pic_square, is_app_user from user where uid in (select uid2 from friend where uid1 = me())";
protected void getFacbookFirends() {
Bundle params = new Bundle();
params.putString("q", QUERY);
final Request req = new Request(getSession(), "/fql", params, HttpMethod.GET, fbCallback);
runOnUiThread(new Runnable() {
#Override
public void run() {
Request.executeBatchAsync(req);
}
});
}
but this is very ugly, so I tried using this instead:
Session session = Session.getActiveSession();
if (session == null) {
session = new Session(getActivity());
}
if (session != null && session.isOpened()) {
Request req = Request.newGraphPathRequest(session, "/me/friends?fields=id,name,installed,picture",
new Callback() {
#Override
public void onCompleted(Response response) {
Log.w("FriendsListFragment.Facebook.onComplete", response.toString());
}
});
Request.executeBatchAsync(req);
}
to my understanding, this is the exact same request and should run just the same way, but instead of getting the response I wanted, I get this Response object:
{Response:
responseCode: 400,
graphObject: null,
error: {FacebookServiceErrorException:
httpResponseCode: 400,
facebookErrorCode: 2500,
facebookErrorType: OAuthException,
message: An active access token must be used to query information about the current user.
},
isFromCache:false
}
any thoughts about how I can make this work nicely?
EDIT:
I tried running this code and still got the same result:
Request req = new Request(session, "/me/friends?fields=id,name,installed,picture",null, HttpMethod.GET,
new Callback() {
#Override
public void onCompleted(Response response) {
Log.w("FriendsListFragment.Facebook.onComplete", response.toString());
}
});
Request.executeBatchAsync(req);
Request req = new Request(session, "/me/friends?fields=id,name,installed,picture",null, HttpMethod.GET, .......
Don't put the entire path in the graph path parameter, everything after the ? should be in the params parameter that you set to null. Try this instead:
Bundle params = new Bundle();
params.putString("fields", "id,name,installed,picture");
Request req = new Request(session, "me/friends", params, HttpMethod.GET, .......
That will do the trick.

Android - How to upload photo from the SD card to the Facebook wall

I use the Facebook Android SDK.
Goal
Create multiple posts in news feed of Facebook logged in user that will contain photo from the Android device (its SD card) and some comment. The result should be the same as when you do it using the Add photo/video feature directly in Facebook. In the end, it should look like this:
Wanted Facebook result
Problem
I can't do it.
I went through the numerous similar posts on Stack Overflow, but no answer there so far.
What I have tried to implement so far
Approach 1: SD card photos 2 Facebook album
How
Upload pictures from my mobile (its SD card) to an album that is created for my application the first time I upload a picture from it. In this case, when constructing the params object, I use the picture key and put the bytes of the picture as its value. I use me/photos in the request(...) call of the Facebook (or AsyncFacebookRunner) object. **
The problem
Not all uploaded images are displayed on my wall. Instead, there is something like x photos were added to the album xxx.
The code snippet is this (for one picture)
Bundle params = new Bundle();
params.putString("message", "Uploaded on " + now());
params.putByteArray("picture", bytes); //bytes contains photo bytes, no problem here
asyncRunner.request("me/photos", params, "POST", new PostPhotoRequestListener(), null);
Facebook result
Approach 2: Internet photos 2 facebook news feed
How
Display pictures stored somewhere on the Internet in posts on my wall. In this case, when constructing the params object, I use the link key and set the url to picture as its value. I use me/feed in the request(...) call.
The problem
This produces some strange output, but it isn't what I want.
The code snippet is this (for one picture)
Bundle params = new Bundle();
params.putString("message", "Uploaded on " + now());
params.putString("link", "http://i1114.photobucket.com/albums/k538/tom_rada/bota2.jpg");
asyncRunner.request("me/feed", params, "POST", new PostPhotoRequestListener(), null);
Facebook result
Approach 3: Mix of approach 1 and 2
How
I try to use the picture key and set photo bytes as its value (as in 1.), and call the request with me/feed (as in 2.),
The problem
Message is produced as I would like it to be, but no photo is included
The code snippet is this (for one picture)
Bundle params = new Bundle();
params.putString("message", "Uploaded on " + now());
params.putByteArray("picture", bytes); //bytes contains photo bytes, no problem here
asyncRunner.request("me/feed", params, "POST", new PostPhotoRequestListener(), null);
Facebook result
So, any ideas how I could reach my goal?
EDIT - WORKAROUND FOUND
It seems that the only way to create new posts containing photos on user's wall is to add photos and related comments to user's Wall photos album.
How - Code snippet
Beware: The facebook.request call should be replaced with async call, so the operation doesn't block the UI thread !!!
String wallAlbumID = null;
String response = facebook.request("me/albums");
JSONObject json = Util.parseJson(response);
JSONArray albums = json.getJSONArray("data");
for (int i =0; i < albums.length(); i++) {
JSONObject album = albums.getJSONObject(i);
if (album.getString("type").equalsIgnoreCase("wall")) {
wallAlbumID = album.getString("id");
Log.d("JSON", wallAlbumID);
break;
}
}
... and then
if (wallAlbumID != null) {
Bundle params = new Bundle();
params.putString("message", "Uploaded on " + now());
params.putByteArray("source", bytes);
asyncRunner.request(wallAlbumID+"/photos", params, "POST", new PostPhotoRequestListener(), null);
}
Facebook facebook = new Facebook("your appid");
private void uploadImage()
{
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
final byte[] data = stream.toByteArray();
facebook.authorize(FacebookActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener()
{
#Override
public void onComplete(Bundle values)
{
//uploadImageOnlyToWall(data, "Uploading Image only to wall","Test Post from Android while uploading photo with message");
uploadImageToWallAndAlbums(imageUrl, "Image via link");
}
#Override
public void onFacebookError(FacebookError error)
{
Toast.makeText(FacebookActivity.this, "FaceBook Error", Toast.LENGTH_LONG).show();
}
#Override
public void onError(DialogError e)
{
Toast.makeText(FacebookActivity.this, "Error", Toast.LENGTH_LONG).show();
}
#Override
public void onCancel()
{
Toast.makeText(FacebookActivity.this, "Canceled", Toast.LENGTH_LONG).show();
}
});
}
private void uploadImageOnlyToAlbum(byte[] byteArray,String caption)
{
Bundle params = new Bundle();
params.putByteArray("picture", byteArray);
params.putString("caption",caption);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request("me/photos", params, "POST", new SampleUploadListener(), null);
}
private void uploadImageToWallAndAlbums(byte[] byteArray,String caption)
{
Bundle params = new Bundle();
params.putString("method", "photos.upload");
params.putByteArray("picture", byteArray);
params.putString("caption", caption);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
}
If the user has not previously posted a photo on his/her wall (there is no wall photo album), you can use me/photo request to post a photo first. This will automatically create a wall album.
Facebook facebook = new Facebook("your App_id");
private void uploadImage()
{
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
final byte[] data = stream.toByteArray();
facebook.authorize(FacebookActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener()
{
#Override
public void onComplete(Bundle values)
{
//uploadImageOnlyToWall(data, "Uploading Image only to wall","Test Post from Android while uploading photo with message");
uploadImageToWallAndAlbums(imageUrl, "Image via link");
}
#Override
public void onFacebookError(FacebookError error)
{
Toast.makeText(FacebookActivity.this, " Error", Toast.LENGTH_LONG).show();
}
#Override
public void onError(DialogError e)
{
Toast.makeText(FacebookActivity.this, "Error", Toast.LENGTH_LONG).show();
}
#Override
public void onCancel()
{
Toast.makeText(FacebookActivity.this, "Canceled", Toast.LENGTH_LONG).show();
}
});
}
private void uploadImageOnlyToAlbum(byte[] byteArray,String caption)
{
Bundle params = new Bundle();
params.putByteArray("picture", byteArray);
params.putString("caption",caption);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request("me/photos", params, "POST", new SampleUploadListener(), null);
}
private void uploadImageToWallAndAlbums(byte[] byteArray,String caption)
{
Bundle params = new Bundle();
params.putString("method", "photos.upload");
params.putByteArray("picture", byteArray);
params.putString("caption", caption);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
}
Add this class on your code
public class SampleUploadListener implements RequestListener{
#Override
public void onMalformedURLException(MalformedURLException e, Object state) {
Log.d(TAG, "******************* FACEBOOK::onMalformedURLException *******************");
}
#Override
public void onIOException(IOException e, Object state) {
Log.d(TAG, "******************* FACEBOOK::onIOException *******************");
}
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state) {
Log.d(TAG, "******************* FACEBOOK::onFileNotFoundException *******************");
}
#Override
public void onFacebookError(FacebookError e, Object state) {
Log.d(TAG, "******************* FACEBOOK::onFacebookError *******************");
}
#Override
public void onComplete(String response, Object state) {
Log.d(TAG, "******************* FACEBOOK::onComplete *******************");
}
}

Categories

Resources