Posting image on Facebook timeline using Facebook SDK for Android - android

I have an Android app that posts user's status messages to her/his timeline on Facebook (see the code fragment which posts the message below), the problem is that I cannot post any status images like an emoji. I tried sending the image as a byte array (someone suggested that in another post) to no avail, the picture is rejected and if I post the URL of the image, Facebooks inserts the URL instead of the actual image. Is there a way to have the image posted as a real picture? I'm using Facebook SDK 4.11 for Android and Android Studio 2.1. Any hint will be welcome. Thank you
Here is code:
postParams.putString("caption", getResources().getString(R.string.app_name)); // text to post
postParams.putString("message", msg);
postParams.putString("link", "https://www.terra7.net");
if (imgUrl != null) {
//Bitmap bi = BitmapFactory.decodeResource(getResources(), imgId);
//ByteArrayOutputStream baos = new ByteArrayOutputStream();
//bi.compress(Bitmap.CompressFormat.PNG, 100, baos);
//byte[] data = baos.toByteArray();
//postParams.putByteArray("picture", data); // image to post
postParams.putString("picture", imgUrl); // image to post
}
GraphRequest request = new GraphRequest(accessToken, "me/feed", postParams, HttpMethod.POST, new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
if (response.getError() != null) {
Toast.makeText(MoodFragment.this.getContext(), response.getError().getErrorMessage(), Toast.LENGTH_LONG).show();
}
}
});
request.executeAsync();

Try below code:
public void sharePhotoToFacebook() {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pic);
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(bitmap)
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
ShareApi.share(content, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
Log.e("onSuccess ", "result " + result);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
Log.e("onError ", "error " + error);
}
});
}
For using above code you need publish_actions permission you can use below code for get permission:
public void getPermission() {
List<String> permissionNeeds = Arrays.asList("publish_actions");// - See more at: http://simpledeveloper.com/how-to-share-an-image-on-facebook-in-android/#sthash.v7b5g7GA.dpuf
loginManager = LoginManager.getInstance();
loginManager.logInWithPublishPermissions(this, permissionNeeds);
loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
sharePhotoToFacebook();
}
#Override
public void onCancel() {
System.out.println("onCancel");
}
#Override
public void onError(FacebookException exception) {
System.out.println("onError");
}
});
// - See more at: http://simpledeveloper.com/how-to-share-an-image-on-facebook-in-android/#sthash.v7b5g7GA.dpuf
}

Related

Unable to share photo in Facebook

I am taking a photo using an Android phone, and I want to post it in Facebook. My code:
private void SharePhotoFacebook(Bitmap bmp) {
FacebookSdk.sdkInitialize(FaceActivity.this);
// Create a callbackManager to handle the login responses.
callbackManager = CallbackManager.Factory.create();
shareDialog = new ShareDialog(this);
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(bmp)
.build();
if(ShareDialog.canShow(SharePhotoContent.class)){
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
shareDialog.show(content);
}
// this part is optional
shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
Log.i("David", "Éxito");
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
Log.i("David", "Error");
}
});
}
But no dialog is showing, and nothing is posted in Facebook. I have implemented this code in the same Activity I take photo (FaceActivity), and is the Activity declared in Facebook Developer page of the app. What is wrong?
I can see like something tries to show (a grey "flash" that appears in the screen) but nothing shows.
EDIT: Im taking photo this way:
makePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCameraSource.takePicture(null, new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(#NonNull byte[] bytes) {
Log.i("David", String.valueOf(bytes.length));
bmp= BitmapFactory.decodeByteArray(bytes,0,bytes.length);
ShowShareDialog();
//SharePhotoFacebook(bmp);
}
});
}
});
I just realized I have this in my debug:
Unsupported get request. Object with ID 'XXXXXXX' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api [extra]:

How to get post permission publish_actions in facebook sdk 4+ with an perfect example

i am not able to get publish_actions permission of facebook sdk4+ i am facing problem and i found there is no proper example available. if any one has the solution do post here. i found that old version solution are shown by everyone but did not found solution for sdk4+ .
LoginManager loginManager = LoginManager.getInstance();
loginManager.logInWithPublishPermissions(this, permissionNeeds);
Log.e("publish_action", "asking_for_permission");
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>()
{
#Override
public void onSuccess(LoginResult loginResult)
{
if (AccessToken.getCurrentAccessToken().getPermissions().contains("publish_actions"))
{
Log.e("publish_action", "permission_activated");
Bitmap image = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
try {
Log.e("publish_action", "permission_activated_inside_try");
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(image)
.setCaption("A post from Android code")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.addPhoto(photo)
.addPhoto(photo)
.build();
ShareApi.share(content, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
Log.e("successfull", "photo_uploaded");
}
#Override
public void onCancel() {
Log.e("canceled", "photo_uploaded_cancled");
}
#Override
public void onError(FacebookException error) {
Log.e("error", "photo_upload_error");
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onCancel() {
System.out.println("onCancel");
Log.e("publish_action", "cancel");
}
#Override
public void onError(FacebookException exception) {
Log.e("publish_action", "error = " + exception.getMessage());
System.out.println("onError");
}
});
I had the same problem, solution was
if (!AccessToken.getCurrentAccessToken().getPermissions().contains("PERMISSION_THAT_YOU_NEED")) {
LoginManager.getInstance().logInWithPublishPermissions((Activity) viewInterface.getContext(), Arrays.asList("PERMISSION_THAT_YOU_NEED"));
return;
You need to return after using logInWithPublishPermissions(), because user may not allow you to use it, but your code will continue to run. And if user provide access to this permission, code will complete successfully next time.
Try this, hope it help to you.
i found this link you must try this url this is a perfect demo for publish_actions permission to facebokk it was helpful for me.

Facebook Posted image shared link not working?

When we post image on facebook by my android app it's post successfully but when we click on that post on Facebook app (on mobile devices) there is a toast appear "There's a problem opening this app." but when open in WEB and click on that posted image it'll redirect to shared link successfully.
I have use this code to share post on facebook.
GraphRequest request = GraphRequest.newPostRequest(AccessToken.getCurrentAccessToken(),
"me/feed", null, new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
Log.i(TAG, response.toString());
//checkPostStatusAndEnableButton();
}
});
Bundle postParams = request.getParameters();
postParams.putString("link",post_url);
postParams.putString("caption", caption);
request.setParameters(postParams);
request.executeAsync();
Is we have use some other action for url for mobile devices?
Try this on :
private static List<String> PERMISSIONS = Arrays.asList("public_profile","user_photos","user_videos", "email","user_likes","user_posts",
"user_hometown", "user_location","user_about_me","user_birthday",
"user_friends","user_relationship_details");
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
Log.i(TAG,"onSuccess registerCallback");
}
#Override
public void onCancel() {
// App code
Log.i(TAG,"onCancel registerCallback");
}
#Override
public void onError(FacebookException exception) {
// App code
Log.i(TAG,"onError registerCallback");
}
});
Then call this share link method :
private void shareLink() {
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentUrl(Uri.parse("https://developers.facebook.com"))
.build();
ShareDialog shareDialog = new ShareDialog(this);
shareDialog.show(content, ShareDialog.Mode.AUTOMATIC);
}

Android Facebook Login- Profile is null

Trying to integrate Facebook Login in android app. The login and logout is working fine but sometimes even after login in, profile is still null. As soon as I get the details from Facebook I logout. I referred to some other questions on Stackoverflow, and applied it in the code but somewhere still something is going wrong and not able to figure it out.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.login_activity);
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.btnFacebookSignin);
loginButton.setReadPermissions("public_profile, email");
loginButton.registerCallback(callbackManager, facebookCallback);
}
FacebookCallback<LoginResult> facebookCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
if(Profile.getCurrentProfile() == null) {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
Log.v("facebook - profile", profile2.getFirstName());
mProfileTracker.stopTracking();
}
};
mProfileTracker.startTracking();
}
else {
Profile profile = Profile.getCurrentProfile();
Log.v("facebook - profile", profile.getFirstName());
}
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
if (BuildConfig.DEBUG) {
FacebookSdk.setIsDebugEnabled(true);
FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
String name = profile.getName();
Uri pictureUri = profile.getProfilePictureUri(200, 200);
String email = object.optString("email");
String uid = object.optString("id");
try {
sendLogin(uid, name, email, pictureUri.toString(), "fb");
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
facebookLogout();
} else {
facebookLogout();
Toast.makeText(getApplication(), "Something went wrong, please try again later", Toast.LENGTH_LONG).show();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
Toast.makeText(getApplication(), "Something went wrong, please try again later", Toast.LENGTH_LONG).show();
}
};
public void facebookLogout() {
LoginManager.getInstance().logOut();
}
Try this Code I hope Its Work..
facebookimage(object.getString("id"));
This is Method:
private void facebookimage(String id) {
new getFacebookImage(id).execute();
}
This is AsyncTask class to get Profile Image on Facebook ;
private class getFacebookImage extends AsyncTask {
String userID;
Bitmap camera;
public getFacebookImage(String id) {
userID=id;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Object doInBackground(Object[] params) {
URL imageURL = null;
Bitmap bitmap=null;
try {
imageURL = new URL("https://graph.facebook.com/" + userID + "/picture?type=large");
bitmap = BitmapFactory.decodeStream(imageURL.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("String Image",""+bitmap);
camera=bitmap;
return bitmap;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
if(camera != null){
Log.e("Image Load","UPload image");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
camera.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte imageInByte[] = stream.toByteArray();
String encodedImage = Base64.encodeToString(imageInByte, Base64.DEFAULT);
DataBase.setUserImage(LoginActivity.this,encodedImage);
}
}
}
Initially I was getting only id and email in JSONObject object of onCompleted. Even though I set permissions like "public_profile" and "email" which is sufficient enough to get the id, name, email and profile picture from facebook. But somewhere I went wrong and didn't understand and added Profile and did getProfile() so I can get the name and profile picture. Then other problem arised was even after login perfectly, I was getting null profile sometimes(may be once in 5 times). For that had to put Profile Tracker and this was because Profile works Asynchronously(was too confusing for me as you have to put trackers and start & stop tracking).
Then I realized where I went wrong. In the bundle where we need to mention what all we want in the json object as reply, I had only mentioned "id". So now in the below code I added "name" and "email" as well. So in the JSONObject object response I get the name and email as well.
And for profile picture I saw How can I display the users profile pic using the facebook graph api? and implemented this using Uri builder Use URI builder in Android or create URL with variables . So with this I removed the use of Profile completely and still getting all the data I wanted.
This answer is the mixture of both the answers mentioned by Destro - Android Facebook Login- Profile is null & How to get email id From Android Facebook SDK 4.6.0?
FacebookCallback<LoginResult> facebookCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
if (BuildConfig.DEBUG) {
FacebookSdk.setIsDebugEnabled(true);
FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
String uid = object.optString("id");
String email = object.optString("email");
String name = object.optString("name");
Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
.authority("graph.facebook.com")
.appendPath(uid)
.appendPath("picture")
.appendQueryParameter("width", "1000")
.appendQueryParameter("height", "1000");
Uri pictureUri = builder.build();
try {
sendLogin(uid, name, email, pictureUri.toString(), "fb");
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
facebookLogout();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
Toast.makeText(getApplication(), "Something went wrong, please try again later", Toast.LENGTH_LONG).show();
}
};
public void facebookLogout() {
LoginManager.getInstance().logOut();
}

have publish_actions approved but facebook post not public

My android application have publish_actions submission were approved but when I post photo on facebook via my application It's not public post because my friend on facebook cannot see this that post.
final String hashTagPost = hashtag;
callbackManager = CallbackManager.Factory.create();
List<String> permissionNeeds = Arrays.asList("publish_actions"); //I added publish_actions
loginManager = LoginManager.getInstance();
loginManager.logInWithPublishPermissions(this, permissionNeeds);
loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(bitmap)
.setCaption(txtCaption.getText().toString() + " #EventPocket " + hashTagPost)
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
ShareApi.share(content, null);
Toast.makeText(PhotoActivity.this, "Post Success", Toast.LENGTH_SHORT).show();
finish();
dialog.dismiss();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
}
This a part of my application.
What I do it more?

Categories

Resources