Android Facebook API publish photo - android

I'm completely lost on this Facebook API for Android, BECAUSE THE DOCUMENTATION IS HORRIBLE!!
Even when I copy their examples to the character, (ammending to fit my app) it still doesn't work!
I have attached to my share button:
Session session = Session.getActiveSession();
if (session.isOpened()) {
OpenGraphAction action = GraphObject.Factory.create(OpenGraphAction.class);
action.setProperty("meal", "https://example.com/cooking-app/meal/Lamb-Vindaloo.html");
action.setType("feed");
Bitmap bitmap;
if (hasIcon) {
bitmap = ((BitmapDrawable)recipeIcon.getDrawable()).getBitmap();
} else {
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_special_rosemary);
}
List<Bitmap> images = new ArrayList<Bitmap>();
if (bitmap != null) {
Log.d("image!", bitmap.getByteCount() + "");
images.add(bitmap);
FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(this, action, "meal")
.setImageAttachmentsForAction(images, true)
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
} else {
Log.d("no image", "");
FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(this, action, "meal")
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
}
This goes through all fine, even the Log tells me the Bitmap is there, is not null, and contains a byteCount of ~160kb, but when I attach it to the share dialog it comes up with this...
01-21 00:39:30.214: E/Activity(2214): Error: com.facebook.FacebookException: Error retrieving image attachment.
What?! Is it not attaching correctly? Well, it mustn't be but this is the example copied direct from their documentation and it doesn't work! I only want to upload the current image. Poor show

Please see the reference docs for the method you're calling - https://developers.facebook.com/docs/reference/android/current/class/FacebookDialog.OpenGraphActionDialogBuilder/#setImageAttachmentFilesForAction
"In order for the images to be provided to the Facebook application as part of the app call, the NativeAppCallContentProvider must be specified correctly in the application's AndroidManifest.xml."
In NativeappCallContentProvider - https://developers.facebook.com/docs/reference/android/current/class/NativeAppCallContentProvider/ - you'll see that you need to add com.facebook.app.NativeAppCallContentProvider{FACEBOOK_APP_ID} to your manifest.

Related

Unity Facebook SDK: post screenshot to wall not working

I am using Unity 4.5, the latest facebook sdk 6.0 and I am working on android right now but it should also work on iOS.
I am trying to take a screenshot and upload it to my wall, therefore I use the standard example scene from the facebook sdk.
Everything works fine when I use my private account as a test account, and it also works with the facebook app ID's of older projects (at least 1 year old). But with a normal account (no tester) and a new facebook app it is not working.
Do I have to do a full submission to use the "post an image to the users wall" function or am I doing something wrong?
My facebook app says "This app is public and available to all users" . So I guess it should work right?
I use this for login:
private void CallFBLogin()
{
FB.Login("email, publish_actions", LoginCallback);
}
void LoginCallback(FBResult result)
{
if (result.Error != null)
lastResponse = "Error Response:\n" + result.Error;
else if (!FB.IsLoggedIn)
{
lastResponse = "Login cancelled by Player";
}
else
{
lastResponse = "Login was successful!";
}
}
And this as screenshot method:
private IEnumerator TakeScreenshot()
{
yield return new WaitForEndOfFrame();
var width = Screen.width;
var height = Screen.height;
var tex = new Texture2D(width, height, TextureFormat.RGB24, false);
// Read screen contents into the texture
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
tex.Apply();
byte[] screenshot = tex.EncodeToPNG();
textureTest = tex;
var wwwForm = new WWWForm();
wwwForm.AddBinaryData("image", screenshot, "InteractiveConsole.png");
wwwForm.AddField("message", "herp derp. I did a thing! Did I do this right?");
FB.API("me/photos", Facebook.HttpMethod.POST, Callback, wwwForm);
}
Hope someone has a solution.
Thank you!
As per the docs. You need to submit your app for review if you require the publish_actions permission.
Review
If your app requests this permission Facebook will have to
review how your app uses it.
When requesting this permission via App Review, please make sure your
instructions are easily reproducible by our team.

Failed to generate preview for user - with common action type

Could someone help me with that? I made a custom story and it works perfectly I just can't figure out what's wrong with this common action type. Window is just opening and closing second after with an exception.
public void publishCommonOpenGraphStory() {
OpenGraphObject book = OpenGraphObject.Factory.createForPost("book");
book.setProperty("title", "Harry Potter");
book.setProperty("description", "Description of HP book.");
book.setProperty("url", "https://www.facebook.com/pages/Harry-Potter-6/115538755123952?rf=376474059116356");
book.setProperty("image", "<img_url>"); // url was long so I cut it there
OpenGraphAction ogAction = GraphObject.Factory.create(OpenGraphAction.class);
ogAction.setProperty("book", book);
ogAction.setType("books.reads");
FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(this, ogAction, "book")
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
Thing is I get an error:
07-25 14:44:19.671 31907-31907/com.example.facebooktest E/ActivityResult.onComplete﹕ Error: com.facebook.FacebookException: Failed to generate preview for user.
I do not know where the problem is, for me everything seems alright.
I figured out what was wrong with that method.
When using common facebook object (like books.book in this example) you have to check which fields are essential (not null) for each object.
I had to add book isbn number as property, which must be filled:
book.getData().setProperty("isbn", "2-07-057267-6");
This can be find in facebook developers site in docs.
Example:
books.book doc
Whole method code looks like this now:
public void publishCommonOpenGraphStory() {
OpenGraphObject book = OpenGraphObject.Factory.createForPost("books.book");
book.setProperty("title", "Harry Potter");
book.setProperty("description", "Description of HP book.");
book.setProperty("url", "https://www.facebook.com/pages/Harry-Potter-6/115538755123952?rf=376474059116356");
book.setProperty("image", "<img link>");
book.getData().setProperty("isbn", "2-07-057267-6");
OpenGraphAction ogAction = GraphObject.Factory.create(OpenGraphAction.class);
ogAction.setProperty("book", book);
ogAction.setType("books.reads");
FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(this, ogAction, "book")
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
}

User Generated Image for Open Graph from Android

I've been following the tutorial to create an open graph story here. Everything works nicely, but I'd like the uploaded image to be large i.e. "user generated".
My problem is in actually implementing that. Here's the code that gets the image from the SD card:
// If uploading an image, set up the first batch request
// to do this.
// Set up image upload request parameters
Bundle imageParams = new Bundle();
Bitmap image = BitmapFactory.decodeFile(getActivity().getIntent().getStringExtra("image_for_facebook"));
// Set up the image upload request callback
Request.Callback imageCallback = new Request.Callback() {
#Override
public void onCompleted(Response response) {
// Log any response error
FacebookRequestError error = response.getError();
if (error != null) {
dismissProgressDialog();
Log.i(TAG, error.getErrorMessage());
}
}
};
// Create the request for the image upload
Request imageRequest = Request.newUploadStagingResourceWithImageRequest(Session.getActiveSession(),
image, imageCallback);
// Set the batch name so you can refer to the result
// in the follow-on object creation request
imageRequest.setBatchEntryName("imageUpload");
// Add the request to the batch
requestBatch.add(imageRequest);
And here's the bit which subsequently gives the graph object its properties:
// Set up the OpenGraphObject representing the book.
OpenGraphObject book = OpenGraphObject.Factory.createForPost("books.book");
// Set up the book image; if we uploaded the image, it is the "uri" result from the previous
// batch request, otherwise it is just a URL.
String imageUrl = "{result=imageUpload:$.uri}";
book.setImageUrls(Arrays.asList(imageUrl));
book.setTitle("A Game of Thrones");
book.setUrl("https://facemash.biz/books/a_game_of_thrones/");
book.setDescription("In the frozen wastes to the north of Winterfell, sinister and supernatural forces are mustering.");
// books.book-specific properties go under "data"
book.getData().setProperty("isbn", "0-553-57340-3");
What do I have to do to set the "user_generated" parameter of the image shown here to be true? (Assuming of course that I'm right in thinking that that's all I have to do to get a large image rather than a thumbnail).
Thanks!
Have a look at the Scrumptious sample, in SelectionFragment.java, the getImageObject method. Basically, you need to create a graph object with the "url" and the "user_generated" properties:
GraphObject imageObject = GraphObject.Factory.create();
imageObject.setProperty("url", "{result=imageUpload:$.uri}");
imageObject.setProperty("user_generated", "true");
GraphObjectList<GraphObject> images = GraphObject.Factory.createList(GraphObject.class);
images.add(imageObject);
book.setImage(images);
Ming's answer came very close for me. In order to attach an image to an OpenGraphAction, I had to do the following:
GraphObject imageObject = GraphObject.Factory.create();
imageObject.setProperty("url", imageUrl);
imageObject.setProperty("user_generated", true);
List<JSONObject> images = new ArrayList<JSONObject>();
images.add(imageObject.getInnerJSONObject());
action.setImage(images);
Open Graph Actions have the method setImage(List<JSONObject> images), but I couldn't find a setImage(GraphObjectList<GraphObject>) method. I'm using Facebook SDK v3.6, so that may have changed.

Upload picture to facebook from unity

Im working on a unity game where you can take a picture and upload this picture to facebook from unity along with some tags and stuff (much like friendsmash). The problem is that i do not have a web-server that i can put the screenshots on, and the Fb.Feeb(picture:) attribute only accepts urls.
I have read that you can use HTTP POST to post the picture to the users images and then use that link in picture:, but i dont know anything about HTTP POST and i couldnt figure out how to do it.
I have also read that you can use FB.API() to somehow do this, but i couldnt figure it out.
Any sample code would be greatly appreciated.
My current code:
private string _path = "file://" + System.IO.Path.Combine(Application.persistentDataPath, "Images/image.png");
void Start ()
{
if (!FB.IsLoggedIn)
FB.Login("email, publish_actions, publish_stream, user_photos", LoginCallback);
StartCamera();
}
private void OnBragClicked()
{
FbDebug.Log("OnBragClicked");
//Post(); <-- dont know how
FB.Feed(
linkCaption: "#hashtag",
picture: "???",
linkName: "Im hashtaging!",
link: "https://apps.facebook.com/" + FB.AppId + "/?challenge_brag=" + (FB.IsLoggedIn ? FB.UserId : "guest")
);
}
void TakeSnapshot()
{
_snap = new Texture2D(_webCamTexture.width, _webCamTexture.height);
_snap.SetPixels(_webCamTexture.GetPixels());
_snap.Apply();
//System.IO.File.WriteAllBytes(_path, _snap.EncodeToPNG());
}
The facebook sdk does have a way to make this happen after all. You need to use Fb.API().
This is the way it worked for me:
private void TakeScreenshot()
{
var snap = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
snap.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
snap.Apply();
var screenshot = snap.EncodeToPNG();
var wwwForm = new WWWForm();
wwwForm.AddBinaryData("image", screenshot, "barcrawling.png");
FB.API("me/photos", HttpMethod.POST, LogCallback, wwwForm);
}
In general terms, to add some sort of caption, it's along the lines...
private byte[] postcardAsBytes;
string textMessage = "Play this great game at http://blah.com.";
Dictionary<string, object> d = new Dictionary<string, object>
{
{ "message", textMessage },
{ "picture", postcardAsBytes }
};
Facebook.instance.graphRequest(
"me/photos", HTTPVerb.POST, d, yourCompletionHandler);
// in this example using the prime31 plugin, rather than the fb sdk
The key field seems to be "message". Confusingly, the "dictionary" field documented by FB, seems to just not work, so try "message" at first.

Android Twitter getting profile image size issue

I'm trying to get the profile images of my followers for use within a ListView as thumbnails.
These thumbnails are around 125x125, but the standard twitter4j call of User.getProfileImageURL(); returns much smaller size of 48x48 and is also recommended to not be used as the image source.
I've tried creating a ProfileImage object and supplying it as a parameter, User.getProfileImageURL(profile image object.Original),
But this code takes some time to simply retrieve the url, which when loading a list of thumbnails, is inefficient.
Any suggestions on how to go about this?
Edit
Twitter API v1 has been disabled, so my old answer is no longer valid. Refer to API v1.1, which I believe requires authentication.
If you know the screen name, the twitter api allows for you to fetch the profile image at 4 different resolutions;
https://api.twitter.com/1/users/profile_image?screen_name=Krylez&size=mini
https://api.twitter.com/1/users/profile_image?screen_name=Krylez&size=normal
https://api.twitter.com/1/users/profile_image?screen_name=Krylez&size=bigger
https://api.twitter.com/1/users/profile_image?screen_name=Krylez&size=original
The "bigger" image is 73x73, which is going to interpolate in your 125x125 container. If you're not okay with this, you can try to fetch the "original" photo, but this photo could be very large (slow) and it's not necessarily a square.
Whatever method you choose, make sure you're not fetching and/or decoding Bitmaps on the UI thread. The Android API documentation has excellent guidelines for the correct way to do this.
Also we can make use of the Twitter4j using:
mTwitter.getUserProfileImage();
From the official doc:
You can obtain a user’s most recent profile image from GET users/show. Within the user object, you’ll find the profile_image_url
and profile_image_url_https fields. These fields will contain the
resized “normal” variant of the user’s uploaded image. This “normal”
variant is typically 48x48px.
By modifying the URL, you can retrieve other variant sizings such as
“bigger”, “mini”, and “original”.
Following the code:
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient();
twitterApiClient.getAccountService().verifyCredentials(false, false, new Callback<User>() {
#Override
public void success(Result<User> userResult) {
String name = userResult.data.name;
String email = userResult.data.email;
// _normal (48x48px) | _bigger (73x73px) | _mini (24x24px)
String photoUrlNormalSize = userResult.data.profileImageUrl;
String photoUrlBiggerSize = userResult.data.profileImageUrl.replace("_normal", "_bigger");
String photoUrlMiniSize = userResult.data.profileImageUrl.replace("_normal", "_mini");
String photoUrlOriginalSize = userResult.data.profileImageUrl.replace("_normal", "");
}
#Override
public void failure(TwitterException exc) {
Log.d("TwitterKit", "Verify Credentials Failure", exc);
}
});
For further information refer to Twitter API Documentation | Profile Images and Banners
To create a custom size pic, for example 90x90 you can use the createScaledBitmap() method.
private final int PROFILE_PIC_SIZE = 90;
Bitmap originalPic = null;
Bitmap resizedPic = null;
try {
InputStream in = new java.net.URL(photoUrlOriginalSize).openStream();
originalPic = BitmapFactory.decodeStream(in);
resizedPic = Bitmap.createScaledBitmap(originalPic, PROFILE_PIC_SIZE, PROFILE_PIC_SIZE, false);
} catch (Exception exc) {
Log.e("Error", exc.getMessage());
exc.printStackTrace();
}
You can use getOriginalProfileImageURL() for example. This is as large as it gets.
Smaller ones are getBiggerProfileImageURL() and getProfileImageURL().
These are the urls you retrieve:
http://pbs.twimg.com/profile_images/NUMBER/c62p-cAD_normal.jpeg
http://pbs.twimg.com/profile_images/NUMBER/c62p-cAD_bigger.jpeg
http://pbs.twimg.com/profile_images/NUMBER/c62p-cAD.jpeg

Categories

Resources