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.
Related
I am trying to build an app which fetches all photos from facebook profile and this code is in the UserProfileActivity. But the intent which starts this activity is inside GraphRequest onCompleted block. This block is never getting executed as I saw while debugging. I tried a lot to understand it and saw various posts and everywhere the code is like this.
public class MainActivity extends AppCompatActivity implements FacebookCallback<LoginResult>{
private LoginButton buttonLoginFacebook;
private TextView textViewMessage;
private CallbackManager callbackManager;
private String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
buttonLoginFacebook = (LoginButton)findViewById(R.id.buttonLoginFacebook);
buttonLoginFacebook.setReadPermissions(Arrays.asList("public_profile, user_photos, user_posts"));
textViewMessage = (TextView)findViewById(R.id.textViewMessage);
buttonLoginFacebook.registerCallback(callbackManager,this);
}
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.e(TAG,object.toString());
Log.e(TAG,response.toString());
try{
String userId = object.getString("id");
URL profilePicture = new URL("https://graph.facebook.com/" + userId + "/picture?width=500&height=500");
String fullName="";
if(object.has("first_name"))
fullName += object.getString("first_name");
if(object.has("last_name"))
fullName += " " + object.getString("last_name");
Intent intent = new Intent(MainActivity.this,UserProfileActivity.class);
intent.putExtra("name",fullName);
intent.putExtra("imageUrl",profilePicture.toString());
startActivity(intent);
finish();
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
textViewMessage.setText("Login attempt cancelled");
}
#Override
public void onError(FacebookException error) {
textViewMessage.setText("Login attempt failed");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
The code is never getting inside the onCompleted block. Thus the intent for UserProfileActivity is never getting executed. I am a little new to Facebook Sdk so any help would be appreciated.
its working for me
LoginManager.getInstance().registerCallback(mCallbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult success) {
// TODO Auto-generated method stub
Log.d("facebookLogin", "successful"
+ success.getRecentlyGrantedPermissions()
.toString() + " " + success.toString());
AccessToken token = success.getAccessToken();
if (token == null) {
Log.e("FBaccessToken", "null");
} else {
Log.d("FBAccesstoken", token.toString());
getFBMeData(token);
}
}
#Override
public void onError(FacebookException e) {
if (e instanceof FacebookException) {
if (AccessToken.getCurrentAccessToken() != null) {
LoginManager.getInstance().logOut();
}
}
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Log.d("facebookLogin", "canceled by user");
}
});
}
public void getFBMeData(AccessToken atoken) {
Profile.fetchProfileForCurrentAccessToken();
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
// TODO Auto-generated method stub
if (object != null) {
Log.d("FBGraphJSONObject", object.toString());
if(Profile.getCurrentProfile()!=null) {
FBdata.put("fbid", Profile.getCurrentProfile()
.getId());
FBdata.put("fname", Profile.getCurrentProfile()
.getFirstName());
FBdata.put("lname", Profile.getCurrentProfile()
.getLastName());
String gender = object.optString("gender");
String dob = object.optString("birthday");
String locationName = "";
JSONObject location = object
.optJSONObject("location");
if (location != null) {
locationName = location.optString("name");
}
String pictureUrl = "", email = "";
JSONObject picture = object
.optJSONObject("picture");
JSONObject data = picture.optJSONObject("data");
try {
email = URLDecoder.decode(
object.optString("email"), "UTF-8");
if (picture != null) {
pictureUrl = URLDecoder.decode(
data.optString("url"), "UTF-8");
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FBdata.put("photo", pictureUrl);
FBdata.put("address", locationName);
FBdata.put("dob", dob);
FBdata.put("gender", gender);
FBdata.put("email", email);
}
}
});
Bundle params = new Bundle();
params.putString("fields", "gender,email,birthday,location,picture");
request.setParameters(params);
request.executeAsync();
}
I had the same problem, The Issue was android.os.NetworkOnMainThreadException,So Make Sure You Call Network Request in a Separate Thread.
This is what i am doing to get user detail. I am able to get FbId,user name and usergender,I wants to get user birthdate too.please check below code Thanks in advance :-
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse response) {
// Application code
if (AccessToken.getCurrentAccessToken() != null) {
if (user != null) {
Log4Android.e(FaceBookLogin.this, user.toString());
// Log.e("onCompleted ", " 1= > " + new Gson().toJson(user));
facebookUser = new Gson().fromJson(user.toString(), FacebookUser.class);
try {
// Log.e("onCompleted ", " 2= > " + new Gson().toJson(user));
Log.e("onCompleted ", " 22= > " + new Gson().toJson(facebookUser));
if (facebookUser.getEmail() != null || !facebookUser.getEmail().equals("")) {
checkUserStatus(context, facebookUser.getId());
} else {
UtilitySingleton.getInstance(context).ShowToast(R.string.email_error);
}
} catch (Exception e) {
e.printStackTrace();
facebookUser = getUsableData(response);
UtilitySingleton.getInstance(context).ShowToast(R.string.email_error);
}
}
}
}
});
Bundle parameters = new Bundle();
// parameters.putString("fields", "id,name,email,first_name,last_name");
parameters.putString("fields", "id,name,email,gender,birthday,first_name,last_name");
request.setParameters(parameters);
request.executeAsync();
What permissions are you asking for?
getting the user birthday requires the permission: "user_birthday".
This solved my proplem:-
String BIRTHDATE = "user_birthday";
public static final String[] FACEBOOK_PERMISSIONS = {ValueKeys.PUBLIC_PROFILE, ValueKeys.EMAIL, BIRTHDATE};
LoginManager.getInstance().logInWithReadPermissions((Activity) context, Arrays.asList(FACEBOOK_PERMISSIONS));
In order to get the permission go to your facebook dashboard >App review > start a submission > and select user_birthday
You can do something along these lines of code -
if (AccessToken.getCurrentAccessToken() != null) {
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse response) {
if (response != null && response.getJSONObject() != null) {
try {
String birthDate = response.getJSONObject().getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields","id,name,email,gender,birthday,first_name,last_name");
request.setParameters(parameters);
request.executeAsync();
}
And you should always check for access token before sending a GraphRequest.
I am attempting to incorporate a Facebook login into my Android Application. The issue that I am having is that I cannot seem to make a successful /me request request with extra parameters.
If I attempt to do a /me request on its own, than I can get the User ID, and Name. I want to get extra fields, such as email, first_name, last_name, etc.
ERROR
{Response: responseCode: 400, graphObject: null, error: {HttpStatus:
400, errorCode: 2500, errorType: OAuthException, errorMessage: An
active access token must be used to query information about the
current user.}}
TRYING TO MAKE REQUEST
I do this from within the onSuccess method inside a LoginManager.
new GraphRequest(
loginResult.getAccessToken(),
"/me?fields=id,name,email",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
}
}
).executeAsync();
I think something is wrong at loginResult.getAccessToken(), try this:
Bundle params = new Bundle();
params.putString("fields", "id,name,email");
new GraphRequest(
AccessToken.getCurrentAccessToken(), //loginResult.getAccessToken(),
"/me",
params,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
try {
Log.e("JSON",response.toString());
JSONObject data = response.getJSONObject();
//data.getString("id"),
//data.getString("name"),
//data.getString("email")
} catch (Exception e){
e.printStackTrace();
}
}
}
).executeAsync();
Check login success with full Permission you want
if (AccessToken.getCurrentAccessToken().getDeclinedPermissions().size() == 0) {
}
I can try to help you out since I just went through the facebook log in and pull back name and email but we really need to see all your code. I'd post all that you can that has anything to do with how you are using facebook classes. Here are parts of what I used if it helps at all:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
loginButtonFacebook = (LoginButton) findViewById(R.id.login_button_facebook);
loginButtonFacebook.setReadPermissions("user_friends,email");
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
accessToken = loginResult.getAccessToken();
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("facebookAccessToken", accessToken.getToken()).apply();
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
getFacebookItems(object);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,first_name,last_name,email,picture");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.d(TAG, "Canceled");
}
#Override
public void onError(FacebookException exception) {
Log.d(TAG, String.format("Error: %s", exception.toString()));
}
});
}
....
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
public void getFacebookItems(JSONObject object){
try {
facebookId = object.getString("id");
facebookName = object.getString("name");
facebookFirstName = object.getString("first_name");
facebookLastName = object.getString("last_name");
facebookEmail = object.getString("email");
}catch (JSONException e) {
e.printStackTrace();
}
}
I also access facebook user friends from another activity so I store my accesstoken in preferences for when I need it later.
accessTokenString = prefs.getString("facebookAccessToken", "");
String facebookId = prefs.getString("facebookId", "");
if (facebookId.length() > 0 && accessTokenString.length() > 0) {
accessToken = new AccessToken(accessTokenString, getString(R.string.facebook_app_id), facebookId, null, null, null, null, null);
storeFacebookFriends();
}
....
public void storeFacebookFriends(){
if (accessToken != null) {
GraphRequestBatch batch = new GraphRequestBatch(
GraphRequest.newMyFriendsRequest(
accessToken,
new GraphRequest.GraphJSONArrayCallback() {
#Override
public void onCompleted(JSONArray jsonArray, GraphResponse response) {
// Application code for users friends
userArray = jsonArray;
}
})
);
batch.addCallback(new GraphRequestBatch.Callback() {
#Override
public void onBatchCompleted(GraphRequestBatch graphRequests) {
// Application code for when the batch finishes
}
});
batch.executeAsync();
}
}
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() {
}
});
}
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;
}
}