Facebook Android SDK - can read profile, but not publish photo to wall - android

I am using this library for intergrating facebook to my app: https://github.com/sromku/android-simple-facebook . It works just fine when accessing profile, friends list, etc. However, when I am trying to publish a photo on the wall, I use the regular SDK, but it does not work. In this case I don't use the library because it does not support publishing photos to wall/pages/groups.
I pass the session I have after requesting publish permissions and fire this request:
public void uploadToFaceWall() {
Session session = mFaceSession;
if (session != null){
String fbPhotoAddress = null;
Request.Callback uploadPhotoRequestCallback = new Request.Callback() {
#Override
public void onCompleted(Response response) {
if (response.getError() != null) {
Log.d(TAG, "error: "+response.toString()):
}
Object graphResponse = response.getGraphObject().getProperty("id");
if (graphResponse == null || !(graphResponse instanceof String) ||
TextUtils.isEmpty((String) graphResponse)) {
Log.d(TAG, "failed photo upload/no response");
} else {
finish();
}
}
};
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeFile(myFacePost.getImages().getString(0), options);
} catch (JSONException e) {
e.printStackTrace();
}
Bundle parameters = new Bundle();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
parameters.putByteArray("picture", byteArray);
parameters.putString("message", "Check out my picture");
Request req = new Request(session, "me/photos", parameters, HttpMethod.POST, uploadPhotoRequestCallback);
req.executeAndWait();
}
}
However, this does not work, and the response contains an error:
{Response: responseCode: 200, graphObject: null, error: {HttpStatus: -1, errorCode: -1, errorType: null, errorMessage: java.lang.NullPointerException}, isFromCache:false}
mFaceSession is the session I have after the user has accepted the new publish permissions.
When debugging I see that the session is OPENED.
Any idea why this does not work?

I've tested your code with the HelloFacebook sample that's shipped with the SDK, replaced here: https://github.com/facebook/facebook-android-sdk/blob/master/samples/HelloFacebookSample/src/com/facebook/samples/hellofacebook/HelloFacebookSampleActivity.java#L351
And it works fine. The possible issue you're facing is the last line req.executeAndWait(); You'll face an exception if you're doing this on the main thread, so update that to req.executeAsync() as in the sample and it should work.
Also see that you get a 200 code which is success, you can see if it worked or not by going to that users timeline. The NullPointerException is probably from this line: Object graphResponse = response.getGraphObject().getProperty("id");.

Related

Facebook API - Sharing Activity

Good day!
I am currently developing a security application that once activates, will automatically get the GPS, send it via SMS, take a photo and then share it through Facebook. I was able to do a simple sharing activity but I'm having trouble automating the Facebook sharing without it showing the preview of the post. The content posted will be inputted by the user so it's not breaking Facebook API regulations. I know that this is possible since some mobile games implement them. Any kind of help would be tremendously appreciated!
I have implemented it some days back like this.....
imageview_fbshare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Util.isDeviceOnline(MainActivity.this)) {
Util.showProDialog(MainActivity.this,"Please wait....");
LoginManager.getInstance().logInWithPublishPermissions(
MainActivity.this,
Arrays.asList("publish_actions"));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
lastimage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Bundle params = new Bundle();
// params.putString("caption", etxt_status.getText().toString());
//params.putString("place", user_loc_id);
//params.putString("tags", ids);
params.putByteArray("picture", byteArray);
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/" + user_id + "/photos",
params,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
//new getPlaceId().execute();
JSONObject o = response.getJSONObject();
try {
String user_status_id = o.getString("id");
} catch (Exception ex) {
}
Util.dimissProDialog();
}
}
).executeAsync();
}
else {
Toast.makeText(MainActivity.this,"OOps! Network Connection Error",Toast.LENGTH_LONG).show();
}
}
});

Unable to upload picture to facebook From android app with different user than me

I have an android app with facebook sdk api integration that allow user to login to facebook and share picture. I've tested my android app by log in with my facebook account (my account is the owner of facebook app) and everithing work well. But if i log in with another account (that is not owner of Facebook app) i'm not able to upload picture. I receive this error;
12-04 13:35:33.484: I/FACEBOOK(20673): {HttpStatus: 403, errorCode: 200, errorType: OAuthException, errorMessage: (#200) Permissions error}
i update picture in this way:
final ProgressDialog spinner = new ProgressDialog(this);
// Part 1: create callback to get URL of uploaded photo
Request.Callback uploadPhotoRequestCallback = new Request.Callback() {
#Override
public void onCompleted(Response response) {
String alert_title = "";
String alert_message = "";
if (response.getError() != null) {
Log.i("FACEBOOK", response.getError().toString());
alert_title = FullPics.this.getString(R.string.alert_error);
alert_message = FullPics.this
.getString(R.string.publish_pic_fail);
} else {
Object graphResponse = response.getGraphObject()
.getProperty("id");
if (graphResponse == null
|| !(graphResponse instanceof String)
|| TextUtils.isEmpty((String) graphResponse)) {
Log.d("FULL", "failed photo upload/no response");
alert_title = FullPics.this
.getString(R.string.alert_error);
alert_message = FullPics.this
.getString(R.string.publish_pic_fail);
} else {
alert_title = FullPics.this
.getString(R.string.alert_success);
alert_message = FullPics.this
.getString(R.string.publish_pic_success);
}
}
spinner.dismiss();
showMessage(alert_title, alert_message);
}
};
File image_file = fragmentAdapter.getCurrentImageFile(pager
.getCurrentItem());
Request request;
try {
spinner.setMessage(getString(R.string.publish_pic_in_progress));
spinner.setCancelable(false);
spinner.setCanceledOnTouchOutside(false);
spinner.setProgressStyle(ProgressDialog.STYLE_SPINNER);
spinner.show();
request = Request.newUploadPhotoRequest(
Session.openActiveSession(this, false, null), image_file,
uploadPhotoRequestCallback);
request.executeAsync();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
what's wrong? maybe i need to set something on Facebook developer site inside my app?
This is happening because your facebook app is private to you only. If you observe your app on facebook there will be little green circle which will be shown as disabled if your api is private.
It should public and filled with green color. Then only other user can use this app.
Visit https://developers.facebook.com/docs/games/bestpractice/managing-development-cycle?locale=en_GB for more info
according to new facebook sdk, you need to submit your app for review if you are publishing anything.
after facebook approval you can upload picture by using any login.
you can check this link for review process
https://developers.facebook.com/docs/apps/review/
https://github.com/sauce/guide/wiki/Facebook's-approval-process

facebook integration in android , post photos from all accounts

i have added facebook to my android app to share images and now the thing is that sharing can be done only from my facebook account, whenever i try and login from another account i cannot post any image this is the code snippet that i use . any help is appreciated
`
Request uploadRequest = Request.newUploadPhotoRequest(
Session.getActiveSession(), bmp, new Request.Callback() {
#Override
public void onCompleted(Response response) {
Toast.makeText(FacebookUpload.this,
"Photo uploaded successfully",
Toast.LENGTH_LONG).show();
`
there is a part lyk this
`public void postImage() {
if (checkPermissions()) {
Bitmap bmp = null;
String filename = getIntent().getStringExtra("image");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
Request uploadRequest = Request.newUploadPhotoRequest(
Session.getActiveSession(), bmp, new Request.Callback() {
#Override
public void onCompleted(Response response) {
Toast.makeText(FacebookUpload.this,
"Photo uploaded successfully",
Toast.LENGTH_LONG).show();
File dir = getFilesDir();
File file = new File(dir, "bitmap.png");
file.delete();
}
});
// post on user's wall.
Bundle params =uploadRequest.getParameters();
Random rand = new Random();
int rndInt = rand.nextInt(3)+1;
if(rndInt==1)
params.putString("name", "download Chummi-Lalli Mobile App from https://play.google.com/store/apps/details?id=com.interactive8.readmestories");
else if(rndInt==2)
params.putString("name","Send gifts to your loved ones from www.ekhudol.com");
else if(rndInt==3)
params.putString("name","Chummilalli brought to you by www.3leafsolutions.co.in");
else
params.putString("name","Chummilalli brought to you by www.3leafsolutions.co.in");
uploadRequest.setParameters(params);
uploadRequest.executeAsync();
}
else
requestPermissions();
}`
n whenever i use another account i my code always goes to this else part requestPermission(), why am i redirected here always, everything works fine when i use my own facebook account
it was really simple, i had to do nothing but just submit my app to fb, i didnt know about this step on the developer website, i figured it out and now my app works just fine, thanks though

how long is the FB postId expiration date?

I write an android application which does a FB like to a FB post.
I succeed in doing it, but after a long time I get this response:
{
Response: responseCode: 400,
graphObject: null,
error:
{
HttpStatus: 400,
errorCode: 100,
errorType: OAuthException,
errorMessage: (#100) Error finding the requested story
},
isFromCache:false
}
for the code:
Request request = new Request(
session,
takeFromPublicMacrosOrServer(currentOffer.postId)
+ "/likes", null, HttpMethod.POST,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
// Request complete
if (response.getError() == null) {
UnlockRequestToServer unlockRequestToServer = new UnlockRequestToServer(
mOffersListActivity,
PublicMacros.TYPE_UNLOCK_FB_LIKE,
currentOffer.postId);
} else {
final String errorMsg = "error: "
+ response.getError()
.toString();
Log.e(MyLogger.TAG, errorMsg);
if (BaseApplication
.getCurrentActivity() != null) {
BaseApplication
.getCurrentActivity()
.runOnUiThread(
new Runnable() {
public void run() {
if (PublicMacros.DEBUG) {
Toast.makeText(
BaseApplication
.getCurrentActivity(),
errorMsg,
Toast.LENGTH_LONG)
.show();
}
}
});
}
}
String re = response.toString();
}
});
request.executeAsync();
Does someone know how long is postId valid for FB like action ?
How do I get a page Access Token that does not expire? May contain some useful iformaion for you.
Facebook 3.0 How to post wall? Shows you how to post to your wall
This Question shows you the 'like' Facebook like in android using android.
EDIT
Facebook doesn't notify you that a previously issued access token has
become invalid. Unless you have persisted the expiry time passed to
your App along with the access token, your app may only learn that a
given token has become invalid is when you attempt to make a request
to the API. Also, in response to certain events that are
security-related, access tokens may be invalidated before the expected
expiration time.

Unable to post an image from drawable to facebook

I am trying to pass an image from the drawables folder to the feed dialogue. But I am unable to view the image in facebook feed dialogue. Rest of the parameters are available. I am using facebook SDK 3.5. Here is the function for showing feed dialog.
private void publishFeedDialog() {
Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitMapData = stream.toByteArray();
Bundle params = new Bundle();
params.putByteArray("picture", bitMapData);
params.putString("name", "Facebook SDK for Android");
params.putString("caption", "Build great social apps and get more installs.");
params.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
params.putString("link", "https://developers.facebook.com/android");
//params.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
WebDialog feedDialog = (
new WebDialog.FeedDialogBuilder(getActivity(),
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error == null) {
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(getActivity(),
"Posted story, id: "+postId,
Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(getActivity().getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(getActivity().getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
} else {
// Generic, ex: network error
Toast.makeText(getActivity().getApplicationContext(),
"Error posting story",
Toast.LENGTH_SHORT).show();
}
}
})
.build();
feedDialog.show();
}
Publish feed will work only with url to image.
See picture property under feed documentation: https://developers.facebook.com/docs/reference/dialogs/feed/
If you want to publish image from your memory (like drawable folder) then you need to use: Request.newUploadPhotoRequest()
Beside this, you can use this simple open source library that supports SDK 3.5 for doing actions like publish photo, feed and so on in a very simple way: https://github.com/sromku/android-simple-facebook
UPDATE
Option 1
You can use Request.newUploadPhotoRequest(), but this method doesn't allow you to add any additional property except the image itself.
Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),R.drawable.ic_launcher);
Request.newUploadPhotoRequest(Session.getActiveSession(), bitmap , new Request.Callback()
{
#Override
public void onCompleted(Response response)
{
// ... handle the response...
}
});
Option 2
If you want to add additional properties to the image like description, then do almost the same but with raw graph api call. The facebook implementation of Request.newUploadPhotoRequest() does exactly the same but without setting additional properties.
Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),R.drawable.ic_launcher);
Bundle params = new Bundle();
params.putParcelable("picture", bitmap);
params.putString("message", "This is the description of the image");
params.putString("place", "1235456498726"); // place id of the image
Request request = new Request(session, "me/photos", bundle, HttpMethod.POST, new Request.Callback()
{
#Override
public void onCompleted(Response response)
{
// ... handle the response...
}
});
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();

Categories

Resources