Hello fellow programmers, I having difficulties on the new Facebook SDK,
Scenario is:
im using fragment so I follow this steps
Why doesn't Android Facebook interface work with Fragments?
and now Im getting the oncomplete and the token ID
Now I want to post on my wall so ive created this function
private void publishStory(Session session) {
if (session != null){
// Check for publish permissions
session.addCallback(new StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
List<String> PERMISSIONS = Arrays
.asList("publish_actions");
session
.requestNewPublishPermissions(new Session.NewPermissionsRequest(
getActivity(), PERMISSIONS));
Request request = Request.newStatusUpdateRequest(
session, "Temple Hello Word Sample",
new Request.Callback() {
#Override
public void onCompleted(Response response) {
Log.i("fb:done = ", response.getGraphObject() + ","
+ response.getError());
}
});
request.executeAsync();
}
});
And put the Declaration on the Oncomplete
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
publishStory(session);
}
else
{
Log.v("FACEBOOK ", "NO ACCESS");
}
}
});
}
My problem is on this line of code session.addCallback(new StatusCallback() { it skips the next step thus ending the function without posting on my wall.
I am quite sure that the session is active as I have applicationID and access token..
Any Help?
Thanks
EDIT
Im using this code based on the Answer below and added new permissions
private void publishStoryTEST(final Session session)
{
if (session != null)
{
Bundle postParams = new Bundle();
postParams.putString("message", "TEST");
Request.Callback callback = new Request.Callback()
{
public void onCompleted(Response response)
{
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try
{
postId = graphResponse.getString("id");
}
catch (JSONException e)
{
Log.i("JSON", "JSON error " + e.getMessage());
}
FacebookRequestError error = response.getError();
Log.e("post response", response.toString());
if (error != null)
{
}
else
{
}
}
};
List<String> PERMISSIONS = Arrays
.asList("publish_actions");
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(getActivity(), PERMISSIONS));
Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
But still Im getting an error saying
The user hasn't authorized the application to perform this action
Why is that I still get that error? Does the permission never called?
The problem is common, i am sharing with you the working source code of the Posting Method that i am currently using in my Application.
private void publishStory(String status)
{
Session session = Session.getActiveSession();
if (session != null)
{
Bundle postParams = new Bundle();
postParams.putString("message", status);
Request.Callback callback = new Request.Callback()
{
public void onMalformedURLException(MalformedURLException e)
{
}
public void onIOException(IOException e)
{
}
public void onFileNotFoundException(FileNotFoundExceptione)
{
}
public void onFacebookError(FacebookError e)
{
}
public void onCompleted(Response response)
{
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try
{
postId = graphResponse.getString("id");
}
catch (JSONException e)
{
Log.i("JSON", "JSON error " + e.getMessage());
}
FacebookRequestError error = response.getError();
Log.e("post response", response.toString());
if (error != null)
{
}
else
{
}
}
};
Request request = new Request(session, "me/feed", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
I hope this solves your problem.
EDIT:
Please refer to the following links, for a detailed procedure of setting up Facebook SDK 3.0 with proper permissions and posting features.
Post to facebook after login fails Android
http://www.kpbird.com/2013/03/android-login-using-facebook-sdk-30.html
// Try below code
private void postData() {
lnrPbr.setVisibility(View.VISIBLE);
isSharingData = true;
Session session = Session.getActiveSession();
if (session != null) {
Bundle postParams = new Bundle();
postParams.putString("name", getIntent().getStringExtra("IN_SHARE_CAPTION") == null ? "" : getIntent().getStringExtra("IN_SHARE_CAPTION"));
postParams.putString("caption", getIntent().getStringExtra("IN_SHARE_CAPTION") == null ? "" : getIntent().getStringExtra("IN_SHARE_CAPTION"));
postParams.putString("description", getIntent().getStringExtra("IN_SHARE_DESCRIPTION") == null ? "" : getIntent().getStringExtra("IN_SHARE_DESCRIPTION"));
postParams.putString("link", getIntent().getStringExtra("IN_SHARE_SHARELINK") == null ? "" : getIntent().getStringExtra("IN_SHARE_SHARELINK"));
postParams.putString("picture", getIntent().getStringExtra("IN_SHARE_THUMB") == null ? "" : getIntent().getStringExtra("IN_SHARE_THUMB"));
postParams.putString("message", getIntent().getStringExtra("IN_SHARE_MESSAGE") == null ? "" : getIntent().getStringExtra("IN_SHARE_MESSAGE"));
Request.Callback callback = new Request.Callback() {
public void onCompleted(Response response) {
isSharingData = false;
lnrPbr.setVisibility(View.GONE);
FacebookRequestError error = response.getError();
if (error != null) {
IjoomerUtilities.getCustomOkDialog(getString(R.string.facebook_share_title), error.getErrorMessage(), getString(R.string.ok), R.layout.ijoomer_ok_dialog, new CustomAlertNeutral() {
#Override
public void NeutralMethod() {
finish();
}
});
} else {
IjoomerUtilities.getCustomOkDialog(getString(R.string.facebook_share_title), getString(R.string.facebook_share_success), getString(R.string.ok), R.layout.ijoomer_ok_dialog, new CustomAlertNeutral() {
#Override
public void NeutralMethod() {
finish();
}
});
}
}
};
Request request = new Request(Session.getActiveSession(), "me/feed", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
Refer this tutorial..
http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
Related
I am trying to perform a Facebook Checkin from an Android app that I am developing. I know we have to use the graph API. But I am not sure what all are required to get it working. Is there an example code for this?
I reviewed this link: Publishing checkins on facebook through android app
How do I use this code? Any help on this is appreciated.
public class FBCheckin extends Fragment implements View.OnClickListener {
Button checkin;
public String pageID;
String FACEBOOK_LINK = "https://www.facebook.com/pizzaguydelivery";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
final View rootview = inflater.inflate(R.layout.fblogin, container, false);
checkin.setOnClickListener(this);
return rootview;
}
#Override
public void onClick(View v) {
LoginManager.getInstance().logInWithPublishPermissions(getActivity(), Arrays.asList("publish_actions"));
pageID = FACEBOOK_LINK.substring(FACEBOOK_LINK.lastIndexOf("/") + 1, FACEBOOK_LINK.length());
new GraphRequest(AccessToken.getCurrentAccessToken(), "/" + pageID, null, HttpMethod.GET, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
try {
if (response.getError() == null) {
JSONObject obj = response.getJSONObject();
if (obj.has("id")) {
pageID = obj.getString("id");
Bundle params = new Bundle();
params.putString("message", "Eating");
params.putString("place", pageID);
// params.putString("link", "URL");
if (pageID == null) {
//Toast.makeText(getApplicationContext(),"Failed to check in",Toast.LENGTH_SHORT).show();
} else {
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/feed", params, HttpMethod.POST, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
if (response.getError() == null) {
//success
} else {
//Toast.makeText(getApplicationContext(),"Failed to check in",Toast.LENGTH_SHORT).show();
}
}
}).executeAsync();
}
}
}
} catch (JSONException q) {
// TODO Auto-generated catch block
//Toast.makeText(getApplicationContext(),q.getMessage(),Toast.LENGTH_SHORT).show();
q.printStackTrace();
}
}
}).executeAsync();
}
}
The following code only checks in to locations with facebook pages via pageid. ( Like restaurants.) But think you can do it with place id too.
LoginManager.getInstance().logInWithPublishPermissions(
getActivity(), Arrays.asList("publish_actions"));
String PAGEID = FACEBOOK_LINK.substring(
FACEBOOK_LINK.lastIndexOf("/") + 1,
FACEBOOK_LINK.length());
new GraphRequest(AccessToken.getCurrentAccessToken(), "/"
+ PAGEID, null, HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
try {
if (response.getError() == null) {
JSONObject obj = response
.getJSONObject();
if (obj.has("id")) {
pageID = obj.getString("id");
/* make the API call */
Bundle params = new Bundle();
params.putString("message", "Eating");
params.putString("place", pageID);
params.putString("link","URL");
if (pageID == null) {
MessageBox
.Show(getActivity(),
"Failed to check in to this restaurant");
} else {
new GraphRequest(AccessToken
.getCurrentAccessToken(),
"/me/feed", params,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(
GraphResponse response) {
if (response.getError() == null) {
//success
} else {
MessageBox
.Show(getActivity(),
"Failed to check in to this restaurant");
}
}
}).executeAsync();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
MessageBox.Show(getActivity(),
"Error: " + e.getMessage());
e.printStackTrace();
}
}
}
}).executeAsync();
I know this code is a bit messy but it get the work done. Here the first thing that I am doing is asking user for facebook publish permission. Then I check if the pageID that I am checking into is valid through a graph request. If it is valid then I am checking in the user to his desired location through another request.
Facebook have change API to 4.0
and how can I get user mail address
because new class is called profile can't get that.
It might callback from graph API?
private void GraphAPIprofile() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
Log.i("Graph API", response.toString());
Log.i("User Mail", object.optString("email"));
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
I think there have something wrong with me..
please help, thanks
Try this code:-
if (Session.getActiveSession() == null
|| Session.getActiveSession().isClosed()) {
Session.openActiveSession(this, true, new StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
System.out.println("State= " + state);
if (session.isOpened()) {
System.out.println("Token=" + session.getAccessToken());
Request.executeMeRequestAsync(session,
new GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
System.out.println("User=" + user);
}
if (response != null) {
System.out.println("Response="
+ response);
Toast.makeText(FBConnect.this,
response.toString(),
Toast.LENGTH_LONG).show();
}
}
});
}
if (exception != null) {
System.out.println("Some thing bad happened!");
exception.printStackTrace();
}
}
});
}
Write this code in onResume of your activity or wherever you want to access user's data.
This is my login function:-
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
This my function to get facebook likes and attributes:
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
JSONObject profile = new JSONObject(json);
id=profile.getString("id");
// getting name of the user
name = profile.getString("name");
// getting email of the user
email = profile.getString("email");
//about=profile.getString(about);
bio=profile.getString(bio);
birthday=profile.getString(birthday);
gender=profile.getString(gender);
link=profile.getString(link);
locale=profile.getString(locale);
political=profile.getString(political);
quotes=profile.getString(quotes);
relationship_status=profile.getString(relationship_status);
relegion=profile.getString(relegion);
website=profile.getString(website);
Log.d("Name",name);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
//Getting Facebook Like
Session session = Session.getActiveSession();
new Request(
session,
"/{id}/likes",
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
Log.d("Facebook Likes", response.toString());
}
}
).executeAsync();
/*Session session = Session.getActiveSession();
Request.Callback callback = new Request.Callback() {
#Override
public void onCompleted(Response response) {
// response should have the likes
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
Log.d("Facebook Likes", response.toString());
}
};
Request request = new Request(session, "me/likes", null, HttpMethod.GET, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();*/
ERROR:-
D/Request﹕ Warning: Sessionless Request needs token but missing either application ID or client token.
I am getting other attributes as
28959-29486/com.example.sensetest D/Profile﹕ {"id":"************","email":"***********","first_name":"***","gender":"male","last_name":"****","link":"****","locale":"en_US","middle_name":"Singh","name":"Rituraj Singh Rathore","timezone":5.5,"updated_time":"2015-03-22T11:01:08+0000","verified":true}
The problem is I am not able to get facebook likes of user who has logged in. I have tried also How to get user likes from Facebook with Android sdk 3.0.
But I didn't got desired result.
Help me regarding this, Where am i doing wrong. What should i do to make it right?
I am making an application and I need to get all new notifications from Facebook. I succesfully login and get manage_notifications permission to my App. This piece of code succesfuly load JSON string from facebook.
Session session = Session.openActiveSessionFromCache(ctx);
if (session != null && session.isOpened()) {
Request notificationsRequest = Request.newGraphPathRequest(
session, "/me/notifications",
new Request.Callback() {
#Override
public void onCompleted(Response response) {
GraphObject object = response
.getGraphObject();
if (object != null) {
notificationsNewString = object
.getInnerJSONObject()
.toString();
try {
notificationsOldString = saver.getJsonFromInternalCache();
} catch (IOException e) {
notificationsOldString = null;
}
try {
compareOldAndNewData();
} catch (ParseException e) {
e.printStackTrace();
}
createNotif();
} else {
notificationsNewString = "Notifications returns null";
}
}
});
Request.executeBatchAndWait(notificationsRequest);
} else {
Log.i("TAGTAG", "Session not open!");
}
But some people have difficulties with app, because Facebook dont send in json all new notifications. Especially notification if someone comments on status that they comment. (On Facebook it is marked like a new notification, but json is empty).
Its about some permissions or it is bug?
Thanks.
I found another way. I will post it in case somebody finds it helpful
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
InboxMessage.setVisibility(View.VISIBLE);
new Request(session,"/me/notifications", null,HttpMethod.GET,new Request.Callback() {
public void onCompleted(Response response) {
GraphObject object = response.getGraphObject();
if (object != null) {
InboxMessage.setText(object.getProperty("data").toString());
} else {
InboxMessage.setText("Notifications returns null");
}
}
}
).executeAsync();
} else {
InboxMessage.setVisibility(View.INVISIBLE);
Log.i(TAG, "Logged out...");
}
}
I want to implement "Like" and "Comment" feature in my app. I used this code:
public static void like(String postID) {
String grapPath = String.format("%s/likes", postID);
Request request = new Request(Session.getActiveSession(), grapPath,
null, HttpMethod.POST, new Callback() {
#Override
public void onCompleted(Response response) {
Log.i(TAG, response.toString()+" Success!");
}
});
Request.executeBatchAsync(request);
}
public static void postComment(String comment, String postID) {
String grapPath = String.format("%s/comments", postID);
Bundle bundle = new Bundle();
bundle.putString("message", comment);
Request request = new Request(Session.getActiveSession(), grapPath,
bundle, HttpMethod.POST, new Callback() {
#Override
public void onCompleted(Response response) {
Log.i(TAG, "Success!");
}
});
Request.executeBatchAsync(request);
}
Hhow and where can I call these methods to make them work?
Please make sure the prerequisites are set up correctly. Specifically check out the middle of step 4 to make sure you generated your key hash correctly using your debug keystore.
Otherwise code below should help out
private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions");
}
private void postStatusUpdate() {
if (hasPublishPermission()) {
final String message = "Posting to facebook";
Request request = Request
.newStatusUpdateRequest(Session.getActiveSession(), message, place, tags, new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult(message, response.getGraphObject(), response.getError());
}
});
request.executeAsync();
} else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}