I'm creating an android camera app and I would like to connect it to Facebook.
I created a page for my app and created an Open Graph story "x took a Photo using MyApp".
I'm using a the OpenGraphActionDialogBuilder but for some reason I havnt been able to see the preview of the attached image in the OpenGraphActionDialog which is created.
here is my code:
public void shareWithFacebook(File imageFile) {
// get session
Session session = Session.getActiveSession();
// make sure we have publish permissions
boolean hasPublishPermissions = hasPublishPermission();
if (!hasPublishPermissions) {
if (!session.isOpened()) {
Session.OpenRequest openRequest = new Session.OpenRequest(this);
openRequest.setPermissions("user_friends");
session.openForRead(openRequest);
}
requestPublishPermissions(session);
}
ArrayList<File> files = new ArrayList<File>();
files.add(imageFile);
OpenGraphAction action = OpenGraphAction.Factory.createForPost("mycameraapp:took");
OpenGraphObject picture = OpenGraphObject.Factory.createForPost("mycameraapp:picture");
picture.setProperty("title", "");
action.setProperty("picture", picture);
FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(this, action, "picture" )
.setImageAttachmentFilesForObject("picture", files, true)
.build();
if (FacebookDialog.canPresentOpenGraphActionDialog(this))
shareDialog.present();
}
You need to add:
action.setProperty("previewPropertyName", picture);
Related
I have tried to visit twitter developer website
but i was not getting proper answer from there as i tried different ways to solve this problem but i did found TweetComposer.Builder still i was not able to work with it.
i have found solution for my question i have downloaded and integrated a library from here with the help of this library i am able to post multiple media
Step 1:
first login to twitter by integrating library from this link according to guidance
Step 2:
After that you will be able to login with twitter and you will get two things 1)authToken.token and 2)authToken.secret store this for further use.
Step 3:
public void updateTwitterStatus() {
new AsyncTask() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Object doInBackground(Object[] params) {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(getResources().getString("YOUR_TWITTER_CONSUMER_KEY"));
builder.setOAuthConsumerSecret(getResources().getString("YOUR_TWITTER_CONSUMER_SECRET"));
// Access Token
String access_token = sharedPreferences.getString("authToken.token", "");
// Access Token Secret
String access_token_secret = sharedPreferences.getString("authToken.secret", "");
twitter4j.auth.AccessToken accessToken = new twitter4j.auth.AccessToken(access_token, access_token_secret);
twitter4j.Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status for single image upload with raw folder
StatusUpdate statusUpdate = new StatusUpdate("posted from my app");
InputStream is = getResources().openRawResource(R.raw.lakeside_view);
statusUpdate.setMedia("test.jpg", is);
// Update status for single image upload with file
/*String statusMessage = "posted from my app";
StatusUpdate statusUpdate = new StatusUpdate(statusMessage);
statusUpdate.setMedia(file);*/
// Update status for multiple images upload with file
/*String statusMessage = "Hey I am posting 2 images of xyz event";
File imagefile1 = new File(Environment.getExternalStorageDirectory()+"/images/image_1.jpg");
File imagefile2 = new File(Environment.getExternalStorageDirectory()+"/images/image_2.jpg");
long[] mediaIds = new long[2];
UploadedMedia media1 = twitter.uploadMedia(imagefile1);
mediaIds[0] = media1.getMediaId();
UploadedMedia media2 = twitter.uploadMedia(imagefile2);
mediaIds[1] = media2.getMediaId();
StatusUpdate statusUpdate = new StatusUpdate(statusMessage);
statusUpdate.setMediaIds(mediaIds);*/
// to post twit
twitter4j.Status response = twitter.updateStatus(statusUpdate);
Log.d("Status", response.getText());
} catch (twitter4j.TwitterException e) {
Log.d("Failed to post!", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Object o) {
*//* Dismiss the progress dialog after sharing *//*
Toast.makeText(getApplicationContext(), "Posted to Twitter!", Toast.LENGTH_SHORT).show();
super.onPostExecute(o);
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
i have tried this code it works for me.
Is there any way to post a comment using FacebookSDK 4.0.1.
Because Request was removed in new SDK.
Assume that I had login and got "publish_actions" permission.
private void facebookLogin() {
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("user_friends"));
}
private void facebookLogout (){
LoginManager.getInstance().logOut();
}
private void facebookPost() {
//check login
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken == null) {
Log.d(TAG, ">>>" + "Signed Out");
status = Status.POST;
facebookLogin();
return;
} else {
Log.d(TAG, ">>>" + "Signed In");
status = Status.NONE;
}
if (accessToken.getPermissions().contains("publish_actions")) {
Log.d(TAG, ">>>" + "contain publish_actions");
//I wanna post a comment in here
} else {
Log.d(TAG, ">>>" + "NOT contain publish_actions");
LoginManager.getInstance().logInWithPublishPermissions(this, Arrays.asList("publish_actions"));
}
}
Have you tried sharing using com.facebook.share.widget.ShareApi class
ShareApi.share(content,null);
Assuming that you want to post something on a users wall, here are the steps you need to take in order to use Facebook Post, using Open Graph Stories
1) Head on to the Developer Console
2) Register your application, create the new login flow - be warned the older login flow does not work with SDK 4.0
3) Now once login is working for you, Head on to the Dashboard for this app, select Open Graph from the pane on left.
4) Define your Actions, Stories and Objects here.
5) Although Facebook has given an option to get code, next to the Stories, Action Types and Object Types - be warned this code is old and will not work.
Here is what works for me:
My app name is (as defined on the Dev Console)
friendssampleapp
My Action Type: Celebrating
My Object Type: Milestone
Here is the snippet of code I use to post via a button click:
ShareOpenGraphObject object = new ShareOpenGraphObject.Builder()
.putString("og:type", "friendsampleapp:milestone")
.putString("og:title", "A Game of Thrones")
.putString("og:description", "In the frozen wastes to the north of Winterfell, sinister and supernatural forces are mustering.")
// .putPhoto("og:image", photo)
.build();
// Create an action
ShareOpenGraphAction action = new ShareOpenGraphAction.Builder()
.setActionType("friendsampleapp:celebrating")
.putObject("milestone", object)
.build();
// Create the content
ShareOpenGraphContent content = new ShareOpenGraphContent.Builder()
.setPreviewPropertyName("milestone")
.setAction(action)
.build();
ShareDialog.show(getActivity(), content);
use below code:
Bundle params = new Bundle();
params.putString("message", "This is a test message");
new GraphRequest(
accessToken,
"/me/feed",
params,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
}
}
).executeAndWait();
In my app you can share the video you have just taken. I want to get the link to the video back to android so i can call another function that will input the link in the database. So basically i need to know how to get a link from video i just shared. I am using the following code.
String path;
//get the current active facebook session
Session session = Session.getActiveSession();
//If the session is open
if(session.isOpened()) {
//Get the list of permissions associated with the session
List<String> permissions = session.getPermissions();
//if the session does not have video_upload permission
if(!permissions.contains("video_upload")) {
//Get the permission from user to upload the video to facebook
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(Main_activity.this, Arrays.asList("video_upload"));
session.requestNewReadPermissions(newPermissionsRequest);
}
path = getImagePath(videoUri); //function that gets absolute path
//Create a new file for the video
File file = new File(path);
try {
//create a new request to upload video to the facebook
Request videoRequest = Request.newUploadVideoRequest(session, file, new Request.Callback() {
#Override
public void onCompleted(Response response) {
if(response.getError()==null)
{
Toast.makeText(Main_activity.this, "video shared successfully", Toast.LENGTH_SHORT).show();
Log.i("it","worked");
String atbilde =response.getGraphObject().getProperty("id").toString();
}
else
{
Toast.makeText(Uzdevumi.this, response.getError().getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
});
//Execute the request in a separate thread
videoRequest.executeAsync();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//Session is not open
else {
Toast.makeText(getApplicationContext(), "Please login to facebook first", Toast.LENGTH_SHORT).show();
}
}
});
Edit: Changed the "String atbilde =" so it would store the video id, so now i just need to build the url by simply adding "https://www.facebook.com/video.php?v=" before the id.
The response you receive if the upload of the Video was successful should contain an id property, see
https://developers.facebook.com/docs/graph-api/reference/v2.1/user/videos/#publish
To get a playable URL, you can use this id from the response to query the Graph API like this:
/{video_id}?fields=source
Have a look at https://developers.facebook.com/docs/graph-api/reference/v2.1/video/
i'm developing a simple android app and i want post a status in facebook using OpenGraphObject and OpenGraphAction.
if i use new FacebookDialog.ShareDialogBuilder(this) i have no problem, but when i'm using FacebookDialog.OpenGraphActionDialogBuilder i got the error:
01-09 15:56:29.594 11439-11439/simov.project2.yourcity E/Activity﹕ Error: com.facebook.FacebookException: Failed to generate preview for user.
java
public void test(int position){
File f = (File)mImageAdapter.getItem(position);
Bitmap myBitmap= BitmapFactory.decodeFile(f.getAbsolutePath());
List<Bitmap> images = new ArrayList<Bitmap>();
images.add(myBitmap);
//Session session = Session.getActiveSession();
//session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSION));
try {
addresses = mGeocoder.getFromLocation(mItenerariumState.getCurrentLocation().getLatitude()
, mItenerariumState.getCurrentLocation().getLongitude()
, 1);
} catch (IOException e) {
e.printStackTrace();
}
OpenGraphObject location = OpenGraphObject.Factory.createForPost("yourcity:location");
if(!addresses.isEmpty()){
location.setProperty("title", addresses.get(0).getAddressLine(0));
} else {
location.setProperty("title", "Unknown place");
}
location.setProperty("Description", "I visited this place using YourCity App");
OpenGraphAction action = GraphObject.Factory.create(OpenGraphAction.class);
action.setProperty("location", location);
/* Request request = Request.newPostOpenGraphActionRequest(Session.getActiveSession(), action, new Request.Callback() {
#Override
public void onCompleted(Response response) {
//showPublishResult(getString(R.string.photo_post), response.getGraphObject(), response.getError());
}
});
request.executeAsync();*/
FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(this, action, "yourcity:visit","location")
.setApplicationName("YourCity")
//.setImageAttachmentsForAction(images, true)
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
}
Important note, the shareDialog show in the screen by like one second and then disappears without any action
Have been dealing with this error for hours.
Heres how I fixed it.
The Actions and Objects you specified in your code are the ones that cause the problem.
The samples provided on the Facebook developers guide aren't good enough I feel.
Heres a sample code you can use that will work perfectly.
Basically make sure your ObjectType -> eg: video.other is set correctly and your Action type e.g: video.watches is set right.
void sometestCode(){
OpenGraphObject video = OpenGraphObject.Factory.createForPost("video.other");
video.setTitle("Awesome Video");
video.setDescription("This video will show you how to make the Opengraph work");
OpenGraphAction action = GraphObject.Factory.create(OpenGraphAction.class);
action.setProperty("video", video);
action.setType("video.watches");
FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(this, action, "video")
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
}
We had the exact same error some times ago.
Check you are using the correct action type in OpenGraphActionDialogBuilder.
We fixed the same error just using the correct action type parameter.
In your case you should check if "yourcity:visit" is the name of the action.
Go to developer consolle
https://developers.facebook.com/x/apps/your-app-id/open-graph/action-types/ and click on Get Code for the action you want to implement. Then read the url that should looks like something like this:
https://graph.facebook.com/me/app_namespace:app_action?...
then use the correct app_action in your code. It should fix!
Facebook URL mentioned below return empty data but there is album images in Facebook, i am using new Facebook SDK 3.5.2. anyone have suggestion please help me to come out of this issue.
Thanks on advance
"https://graph.facebook.com/ID/albums?access_token=Token";
I was having the same problem. Read this. Some users dont allow access to their albums and photos through apps. You will have to code accordingly.
Session.NewPermissionsRequest np = new Session.NewPermissionsRequest(this, "friends_photos");
Session.getActiveSession().requestNewReadPermissions(np);
Request rq = new Request(Session.getActiveSession(), userID + "/albums", null, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
}
});
rq.executeAsync();
}
Here is what it should look like. just change userID to the user whose albums you want to retrieve with response being the data that is returned.
I got result by adding below this permissions but i need album list now i get only cover photo and profile picture.
if(session != null && !session.isOpened()){
OpenRequest openRequest = new OpenRequest(this).setCallback(statusCallback);
if (openRequest != null) {
openRequest.setDefaultAudience(SessionDefaultAudience.EVERYONE);
openRequest.setPermissions(Arrays.asList("friends_hometown","user_photos","friends_photos"));
openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
session.openForRead(openRequest);
}
}