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();
}
}
});
Related
I want to share an image on a Facebook page of mine. But I couldn't figure out how to do this step by step. And couldn't find step by step guide for this.
This is my code to share an image on a page
Bundle params = new Bundle();
String nameText = name.getText().toString();
String tags = engine.implodeTags(tagsList);
String textText = text.getText().toString();
params.putString("caption", nameText + "\n\n" + textText + "\n\n" + tags);
params.putString("url", imagesList.get(mainImageSelected).getImageUrl());
params.putString("access_token", "{access token here}");
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/{page_id here}/photos",
params,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
if(response.getJSONObject()!=null) {
Log.d("qwe", response.getJSONObject().toString());
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, "Shared on facebook", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
});
}
else{
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, "Error", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
});
}
}
}
).executeAsync();
It works if I put access token by hand. I am getting access token here
https://developers.facebook.com/tools/explorer .
But after some time this access token is not working any more. So I need to get new access token.
How to get PAGE access token from android itself? Via user login button of facebook sdk?
https://developers.facebook.com/docs/facebook-login/access-tokens
Please help.
Easily if you use facebook SDK to do that. read at here https://developers.facebook.com/docs/sharing/android
You need to get Permanent access token to share images on your Page. To get that you need to follow steps written here.
facebook: permanent Page Access Token?
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");.
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
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();
I am curious if I can get some help with Open Graph since I can't seem to make any sense out of the Facebook API that I have read.
Right now I have setup my Open Graph Application on Facebook. It has been approved. I am trying to submit my "objects" via the bundle params but I am curious how I setup a bundle param object like the following. Where myObject has multiple values associated with it.
Bundle params = new Bundle();
param.putString("myObject", ""); // My object has multiple values
I guess I really need to figure out how you submit something in the Bundle that has multiple properties associated with it. If anyone has any insight on this please help me out.
At first I had tried something like this.
Bundle myObject = new Bundle();
myObject("property1", "property1Value");
myObject("property2", "property2Value");
myObject("property3", "property3Value");
Bundle params = new Bundle();
params.putString("myObject", myObject);
But in hindsight I figured out why this wouldn't work.
Edit 1
Maybe this will shed some light. Keep in mind this is an Open Graph action which is not a part of the Graph API.
//Build recipe
JSONObject recipe = new JSONObject();
recipe.put("type", "myappns:recipe");
recipe.put("recipe_name", "Thai Island");
recipe.put("cook_time", "1hr. 30min.");
//Build cookbook
JSONObject cookbookParams = new JSONObject();
cookbookParams.put("type", "myappns:book");
cookbookParams.put("title", "Hot & Spicy");
cookbookParams.put("description", "This book consists of hot & spicy foods");
cookbookParams.put("recipes", new JSONArray().put(recipe));
Bundle params = new Bundle();
params.putString("cookbook", cookbookParams.toString());
AsyncFacebookRunner request = new AsyncFacebookRunner(facebook);
request.request("me/myappns:used", params, "POST", new addToTimelineListener(), null);
Here is a question though as I have been digging more into the Open Graph system. I believe I need to actually have a website setup somewhere, is this correct? I was lead to believe through the introductory documentation of Open Graph that I could create and use my Facebook application on Android without the need of any website. That is use the Open Graph system, I know I can use the application to post feeds and what not which I have done successfully.
Thanks again!
Edit 2
Dont even worry about replying I understand what my problem was now...I have to have a website somewhere hosting a Facebook application for the posts to link back too. Makes perfect sense, I haven't seen where the documentation was very direct about this...oh well now I know.
I use this code to publish on wall for multiple object properties.
private void publishPhoto(String imageURL) {
Log.d("FACEBOOK", "Post to Facebook!");
try {
JSONObject attachment = new JSONObject();
attachment.put("message",text);
attachment.put("name", "MyGreatAndroidAppTest");
attachment.put("href", "http://stackoverflow.com/users/909317/sunny");
attachment.put("description","Test Test TEst");
JSONObject media = new JSONObject();
media.put("type", "image");
media.put("src", imageURL);
media.put("href",imageURL);
attachment.put("media", new JSONArray().put(media));
JSONObject properties = new JSONObject();
JSONObject prop1 = new JSONObject();
prop1.put("text", "Text or captionText to Post");
prop1.put("href", imageURL);
properties.put(text, prop1);
// u can make any number of prop object and put on "properties" for ex: //prop2,prop3
attachment.put("properties", properties);
Log.d("FACEBOOK", attachment.toString());
Bundle params = new Bundle();
params.putString("attachment", attachment.toString());
facebook.dialog(MyProjectActivity.this, "stream.publish", params, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Log.d("FACEBOOK", "Dialog Success! post_id=" + postId);
Toast.makeText(MyProjectActivity.this, "Successfully shared on Facebook!", Toast.LENGTH_LONG).show();
} else {
Log.d("FACEBOOK", "No wall post made");
}
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
} catch (JSONException e) {
Log.e("FACEBOOK", e.getLocalizedMessage(), e);
}
}
To see a complete example look at the wishlist example.
A complete example for Android is included. The package includes the files to be uploaded on the server and a readme file that explain how to set up all the stuff on the open graph panel.