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
Related
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();
}
}
});
My Android app should offer the functionality of sharing files via google drive:
1) upload a file (which was selected previously from the sd-card) to google drive
2) get back a link (url) to the uploaded file
3) share this link with other users of the app
4) other users may download the shared file to the sd-card of their device
All this functionality should be available in the app, without having the need to use a browser.
Does anyone have an idea how i can implement the steps 1, 2 and 4?
thanks in advance!
gerhard
This can help you for Google Drive file upload -
First, go for authentication
AccountManager am = AccountManager.get(activity);
am.getAuthToken(am.getAccounts())[0],
"oauth2:" + DriveScopes.DRIVE,
new Bundle(),
true,
new OnTokenAcquired(),
null);
Now need to set token
private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
#Override
public void run(AccountManagerFuture<Bundle> result) {
try {
final String token = result.getResult().getString(AccountManager.KEY_AUTHTOKEN);
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
#Override
public void initialize(JSonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest.setKey(CLIENT ID YOU GOT WHEN SETTING UP THE CONSOLE BEFORE YOU STARTED CODING)
driveRequest.setOauthToken(token);
}
});
final Drive drive = b.build();
final com.google.api.services.drive.model.File body = new
com.google.api.services.drive.model.File();
body.setTitle("My Test File");
body.setDescription("A Test File");
body.setMimeType("text/plain");
final FileContent mediaContent = new FileContent("text/plain",
"Your data")
new Thread(new Runnable() {
public void run() {
try {
com.google.api.services.drive.model.File file =
drive.files().insert(body, mediaContent).execute();
alreadyTriedAgain = false;
} catch (IOException e) {
if (!alreadyTriedAgain) {
alreadyTriedAgain = true;
AccountManager am = AccountManager.get(activity);
am.invalidateAuthToken(am.getAccounts()[0].type, null); // Requires the permissions MANAGE_ACCOUNTS & USE_CREDENTIALS in the Manifest
am.getAuthToken (same as before...)
} else {
// Give up. Crash or log an error or whatever you want.
}
}
}
}).start();
Intent launch = (Intent)result.getResult().get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, 3025);
return; // Not sure why... I wrote it here for some reason. Might not actually be necessary.
}
} catch (OperationCanceledException e) {
// Handle it...
} catch (AuthenticatorException e) {
// Handle it...
} catch (IOException e) {
// Handle it...
}
}
}
Now, To update the file
public void updateFile(Drive drive, File gFile, java.io.File jFile) throws
IOException {
FileContent gContent = new FileContent("text/csv", jFile);
gFile.setModifiedDate(new DateTime(false, jFile.lastModified(), 0));
gFile = drive.files().update(gFile.getId(), gFile,
gContent).setSetModifiedDate(true).execute();
}
Also, Don't fget to give permissions in Manifest for
GET_ACCOUNTS, USE_CREDENTIALS, MANAGE_ACCOUNTS, INTERNET WRITE_EXTERNAL_STORAGE
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/
GOAL
In my camera app i want to let user share a picture with pre-formatted text and a description on the user's facebook wall.
INTRO
I Googled a lot and followed "the terrific" facebook-getting-started, trying many things, for !!days!!... no completely working solutions found yet.
At least i think i got some points:
The great Android Intent action_send works great but not choosing facebook, that works for text OR for pictures, not for both (!!), see here
applicationID, hashxxx, and everything else needed to link android app to facebook login, all things that i really don't understand and don't want to, done and at last working (thanx facebook for all this sh*t!!)
share with facebook can be done (see here):
3a. using the facebook app (installed in the device)
3b. using a login session (if facebook app is not installed)
Facebook wants us to use its SDK, it's very [b|s]ad, but i can stand it.
case 3a - facebook suggests us to use the shareDialog, and -fighting a lot with code snippets and samples suggested!- i have been able to do it, but i need it to work also if facebook app is not installed (case 3b.)
case 3b - facebook suggests to use the "ugly" feedDialog as a fallback (see here).
6a. feedDialog needs login and it's ok...
6b. it seems feedDialog cannot share local images, i really don't understand why... here facebook guide talks only about "URL" for the "picture" keyword...
5c. then i think i must use Request, i tried implementing it but nothing happened, i think i'm missing something... No useful references (=working examples) found.
CODE SNIPPETS copy/paste/edit from SO and developers.facebook
ShareDialog and session management in case facebook app is not installed IT'S WORKING
/**
* share image with facebook, using facebook sdk
* #param pathToImage
*/
private void shareWithFacebook(String pathToImage) {
Log.i("SHARE", "share with facebook");
if (FacebookDialog.canPresentShareDialog(getApplicationContext(), FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) {
// Publish the post using the Share Dialog
Log.i("SHARE", "share with ShareDialog");
FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(this)
.setCaption("Sharing photo taken with MyApp.")
.setName("Snail Camera Photo")
.setPicture("file://"+pathToImage)
.setLink("http://myapplink")
.setDescription("Image taken with MyApp for Android")
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
} else {
// maybe no facebook app installed, trying an alternative
// here i think i need a session
if (Session.getActiveSession() != null && Session.getActiveSession().isOpened()) {
publishFeedDialog(pathToImage);
} else {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
List<String> permissions = new ArrayList<String>();
permissions.add("publish_actions");
session.openForRead(new Session.OpenRequest(this)
.setPermissions(permissions)
.setCallback(mFacebookCallback));
} else {
Session.openActiveSession(this, true, mFacebookCallback);
}
}
}
}
private Session.StatusCallback mFacebookCallback = new Session.StatusCallback() {
public void call(final Session session, final SessionState state, final Exception exception) {
if (state.isOpened()) {
String facebookToken = session.getAccessToken();
Log.i("SHARE", facebookToken);
Request.newMeRequest(session, new Request.GraphUserCallback() {
public void onCompleted(GraphUser user, com.facebook.Response response) {
publishFeedDialog(MP.LAST_TAKEN_FOR_GALLERY);
}
}).executeAsync();
}
}
};
feedDialog snippet, works for text fields, links, and remote url, but DOESN'T WORK FOR LOCAL PICTURES using "file://..." nor "file:///...". Error message: picture URL is not properly formatted.
private void publishFeedDialog(String pathToImage) {
Bundle params = new Bundle();
params.putString("name", "myapp Photo");
params.putString("caption", "Sharing photo taken with myapp.");
params.putString("description", "Image taken with myapp for Android");
params.putString("link", "http://myapp.at.playstore");
params.putString("picture", "file://"+pathToImage);
WebDialog feedDialog = (
new WebDialog.FeedDialogBuilder(EnhancedCameraPreviewActivity.this,//getApplicationContext(),
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener() {
public void onComplete(Bundle values,
FacebookException error) {
Log.i("SHARE", "feedDialog.onComplete");
if (error == null) {
// story is posted
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(getApplicationContext(),
"Posted story, id: "+postId,
Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
} else {
// Generic, ex: network error
Toast.makeText(getApplicationContext(),
"Error posting story",
Toast.LENGTH_SHORT).show();
}
}
})
.build();
feedDialog.show();
}
Another try, using Request, it says:
photo upload problem. Error={HttpStatus: 403, errorCode: 200,
errorType: OAuthException, errorMessage: (#200) Requires extended
permission: publish_actions}
I tried adding publish_actions permission in the session management above, maybe i miss something...
private void publishFeedDialog(String pathToImage) {
Request request=Request.newPostOpenGraphObjectRequest(
Session.getActiveSession(),
"PhotoUpload",
"myApp Photo Upload",
"file://"+pathToImage,
"http://myapp.at.playstore",
"Image taken with myApp for Android",
null,
uploadPhotoRequestCallback);
request.executeAsync();
}
Last try with Request, absolutely nothing happens, both with or without "picture" keyword.
private void publishFeedDialog(String pathToImage) {
Bundle parameters = new Bundle();
parameters.putString("message", "Image taken with myApp for Android");
parameters.putString("picture", "file://"+pathToImage);
parameters.putString("caption", "myApp Photo");
Request request = new Request(Session.getActiveSession(), "/me/feed", parameters, null);
// also tried: Request request = new Request(Session.getActiveSession(), "/me/feed", parameters, com.facebook.HttpMethod.POST);
request.executeAsync();
}
QUESTIONS
-1- Are there some faults in my 1..6 points?
-2- Can i share a local picture using FeedDialog?
-3- if not, how to when facebook app is not installed?
Thanks a lot!
I have the same problem, but I have a workaround.
I can't find any wrong reasoning in your point 1-6, look like the same issues I've come acrossed.
You can't share pictures locally, but...
Code snippet below:
This will upload the picture to the users profile and post it on his\hers wall, afterwhich you can get the URL if needed:
private void uploadPicture(final String message, Session session) {
Request.Callback uploadPhotoRequestCallback = new Request.Callback() {
#Override
public void onCompleted(com.facebook.Response response) {
if (response.getError() != null) {
Toast.makeText(getActivity(), "Failed posting on the Wall", Toast.LENGTH_LONG).show();
return;
}
Object graphResponse = response.getGraphObject().getProperty("id");
if (graphResponse == null || !(graphResponse instanceof String) ||
TextUtils.isEmpty((String) graphResponse)) {
Toast.makeText(getActivity(), "Failed uploading the photo\no respons", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Succsefully posted on the facebook Wall", Toast.LENGTH_LONG).show();
}
}
};
// Execute the request with the image and appropriate message
Request request = Request.newUploadPhotoRequest(session, profileBitmap, uploadPhotoRequestCallback);
Bundle params = request.getParameters();
params.putString("message", message);
request.executeAsync();
}
And to start facebook login when you don't have the APP, it's simpler, I use the following code snippet for calling the facebook SDK on facebook button:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.faceBookButton:
if (((imagePath != null && !imagePath.equals("")) || (message != null && !message.equals("")))) {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForPublish(new Session.OpenRequest(this)
.setPermissions(Arrays.asList("public_profile", "publish_actions"))
.setCallback(statusCallback));
} else {
if (profileBitmap != null) {
uploadPicture(message, session);
} else {
publishFeedDialog(message);
}
}
} else {
Toast.makeText(getActivity(), getString(R.string.checkin_fail), Toast.LENGTH_SHORT).show();
}
break;
}
}
In my case publishFeedDialog accepts the message you want to pass on, and not the image, but it doesn't matter. It opens up Facebook's message dialog anyway to which I haven't yet found a way to pass a predefined message from my EditText widget.
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();