In an Android App I have the following code:
private void requestDataFromFb() {
Callback callback = new Callback() {
#Override
public void onCompleted(Response response) {
AppLog.Log(TAG, "Facebook Response ::" + response + "");
Utility.closeprocess(Login.this);
loadImage(response);
}
};
String graphPath = "me";
Bundle bundle = new Bundle();
bundle.putString("fields",
"id,picture.height(250),gender,first_name,last_name,age_range");
Request mRequest = new Request(Session.getActiveSession(), graphPath,
bundle, HttpMethod.GET, callback);
RequestAsyncTask task = Request.executeBatchAsync(mRequest);
if (task == null) {
AppLog.Log(TAG, "task is null");
} else {
AppLog.Log(TAG, task.getStatus() + "");
}
}
It's been working fine and I am getting the paths to the user's profile picture. However, after some time the paths don't work anymore. One cannot see the picture of the first users. When I enter the URL in my browser I get:
An error occurred while processing your request.
Reference #50.3d1431b5.1424197137.a584ec67
And when using the Graph API Explorer of Facebook I get a different URL for the picture.
I do not know if that has something to do with the fact that the user has changed their profile picture or something else, and how I could solve this issue.
Any advise or guidance would be greatly appreciated
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 having an app using FB android SDK v 4.5 where i want to upload image to facebook custom story directly from device or camera. i have created custom story even enabled user generated photo option in story setting(in object or action) in.
below is code snippet i am try to use for custom story post.
How to attach image to directly to this code from device
String shareTitle = bundle.getString("shareTitle");
String shareUrl = bundle.getString("shareUrl");
Bundle params = new Bundle();
JSONObject myObject = new JSONObject();
try {
myObject.put("og:type", "in_myappnamespace:check_in");
myObject.put("og:title", "Check out what i found on #myapptag "
+ shareTitle);
if (shareUrl != null && !shareUrl.equalsIgnoreCase("")) {
myObject.put("og:url", shareUrl);
}
} catch (JSONException e) {
}
params.putString("check_in", myObject.toString());
params.putString("fb:explicitly_shared", "true");
fbGraphRequest = new GraphRequest(AccessToken.getCurrentAccessToken(),
"me/in_myappnamespace:share", params, HttpMethod.POST);
new Thread() {
public void run() {
final GraphResponse response = fbGraphRequest.executeAndWait();
}}.start();
please help me, how to attach image with this request from android device.
thanks,
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();
I want to get a list of a users albums names and ids. You need to add the permission users_photos for this.
I created a method called fetchAlbums, and in it I am requesting additional permissions. But by the time the permissions dialog pops up, the rest of the method has already executed (without the needed permissions!).
Whats the best way to do this, add the permissions in the onCreate of the Activity?
private void fetchAlbumsFromFB() {
Session session = Session.getActiveSession();
// make a new async request
Bundle params = new Bundle();
params.putString("fields", "id, name");
new Request(
session,
"/me/albums",
params,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
// use response id to upload photo to that album
//errText.setText("New Album created response: " + response.toString());
//need to get the newly created album ID.
try{
JSONObject graphResponse =response.getGraphObject().getInnerJSONObject();
Toast.makeText(getApplicationContext(), "Albums " + graphResponse.toString(), Toast.LENGTH_LONG).show();
}
catch (Exception e) {
e.printStackTrace();
albID = null;
}
}
}
).executeAsync();
}
It's better to ask for user_photos permission at the starting point, when the user is authenticating the app the first time.
Since it's not an extended/publish permission, it will be asked along with the basic permissions and user wont bother too; else user will see the permission dialogs again and again that could frustrate him.
I guess, in that case this problem will be solved too.
I'm writting app integrated with facebook. I want to post to wall without post dialog. I try to use code from this answer, but I got an error
{"error":
{"message":"An active access token must be used to query information about the current user.",
"type":"OAuthException",
"code":2500
}
}
I login user with this code
public void authorize() {
mFacebook.authorize(mActivity, new String[] { "publish_stream" }, new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", mFacebook.getAccessToken());
editor.putLong("access_expires", mFacebook.getAccessExpires());
editor.commit();
mLoginStateView.setImageResource(mAuthorizedDrawableRes);
}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
Please, explain me what am I doing wrong?
[ADDED]
If I try to post with mFacebook.dialog(currentActivity, "stream.publish", params, new UpdateStatusListener()); it works. Please, help me!
A successful authorization would return an access token to your app, which you can then use to perform actions to the Facebook API. The error message displayed means you do not have a valid access token which means you probably did not authenticate the app correctly. I would put some logging on the onFacebookError and onError methods to see what the problem is.
Oh, I've done it. But it looks like a bug or magic...
LogCat after authorize method (Facebook's log is enabled)
Facebook-authorize: Login Success! access_token=AAAHL4f6XMS0BAHNJKpoGAUAeGDlynRt1s5XPdBPRWGfILGOTZB4OSEGi4HBPLZBXDWqK2RIO8disDtzxHBYSvL3bZAnHkU5hAVK9oqWhAZDZD expires=1356040438476
But then I try post with
String response = mFacebook.request("me/feed", parameters, "POST");
Function request from Facebook.java :
public String request(String graphPath, Bundle params, String httpMethod)
throws FileNotFoundException, MalformedURLException, IOException {
params.putString("format", "json");
if (isSessionValid()) {
params.putString(TOKEN, getAccessToken());
}
String url = (graphPath != null) ? GRAPH_BASE_URL + graphPath : RESTSERVER_URL;
return Util.openUrl(url, httpMethod, params);
}
I see in debugger, that Facebook's function isSessionValid() returns false and mAccessToken = null. I don't know why it is so, and why it returns true sometimes afterwards (yes, I understand that it is impossible). Explaine me, please, if you know.
This code solved my problem (it just re-sets access token)
if (!mFacebook.isSessionValid()){
String token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
mFacebook.setAccessToken(token);
mFacebook.setAccessExpires(expires);
}
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putString("description", "test test test");
String response = mFacebook.request("me/feed", parameters, "POST");
if (response == null || response.equals("") || response.equals("false")) {
Log.e(Const.LOG_TAG, "Blank response");
} else {
Log.d(Const.LOG_TAG, response);
}
I also had the same problem while retrieving albums from facebook. I tested my access_token via facebook debugger and it was valid. Then I found the error, the final url in com.facebook.android.Util.openUrl(...) was:
Invalid-URL1:
https:// graph.facebook.com//me/albums?fields=id,name,cover_photo,type,count?access_token={...token..}&format=json&metadata=1
Where it should be:
Valid - URL2:
https:// graph.facebook.com//me/albums?fields=id,name,cover_photo,type,count&access_token={...token..}&format=json&metadata=1
Note that in URL1 ? is added two times which is not valid so I changed the code as follows
Code Changes:
Previous
com.facebook.android.Util.openUrl(...)
if (method.equals("GET")) {
url = url + "?" + encodeUrl(params);
}
Now
com.facebook.android.Util.openUrl(...)
if (method.equals("GET")) {
if(url.contains ( "?" )==false)
{
url = url + "?" + encodeUrl(params);
}
else
{
url = url + "&" + encodeUrl(params);
}
}