Facebook android SDK4.0 get mail address - android

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.

Related

Facebook user birthday using Graph Request android?

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.

newMeRequest's onCompleted method user is always null

When I make newMeRequest using Facebook Android SDK
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Log.e(TAG, "Logged in..." + user.getName());
} else {
Log.e(TAG, "Logged in... but user==null");
}
}
}).executeAsync();
Logcat says "Logged in.. but user==null"
what should I do?
Maybe you can add a parameter with specific fields :
Request request = Request.newMeRequest(currentSession, new Request.GraphUserCallback() {
....
}
Bundle parameters = new Bundle();
// REQUEST_FIELDS : id,name,email
parameters.putString(FIELDS, REQUEST_FIELDS);
request.setParameters(parameters);
Request.executeBatchAsync(request);

Post on FB wall Using 3.0 SDK

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() {
}
});
}

Android Facebook native app not getting user email and birthday even with permissions set and correct information in fields

I'm trying to get the user email and birthday (using a Me request). My app has email and user_birthday permissions and the fb account i'm using has an email and a birthday set.
When I try using the 'Graph API Explorer' (https://developers.facebook.com/tools/explorer) using the user access_token with 'fields=id,email,birthday' all I get is the id.
Can anybody advice me on this please.
Here is my code:
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// here I check the infos I got.
Log.d("some tag", user.getInnerJSONObject().toString()); // it shows only the id, no email or birthday.
if (Session.getActiveSession() != null) {
Log.i(TAG, "Log out from FB");
Session.getActiveSession().closeAndClearTokenInformation();
}
}
}
});
// set params.
request.getParameters().putString("fields", "id,email,birthday");
// execute request.
request.executeAsync();
Log.d(TAG, request.toString());
}
if (exception != null) {
exception.printStackTrace();
}
}
});
Many thanks.
I finally changed the approach using the OpenRequest instead of getMeRequest:
Here is my code:
public void onClick(View v) {
Logger.d(TAG, "Start FB session");
// check if a session exists.
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
// create a new session.
Session session = new Session.Builder(getApplicationContext()).build();
// set it a the active session.
Session.setActiveSession(session);
// keep a variable link to session.
currentSession = session;
}
// if a session is already open then issue a request using the available
// session. Otherwise ask for user credentials.
if (currentSession.isOpened()) {
// The user is logged in.
Logger.e(TAG, "User is logged in.");
Session.getActiveSession().closeAndClearTokenInformation();
Logger.i(TAG, "Session closed an token information cleared.");
// get user data here with no extra call.
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
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) {
if (user != null) {
Logger.i(TAG, "User:" + user.getInnerJSONObject());
}
}
});
}
}
});
} else {
// Ask for username and password
OpenRequest op = new Session.OpenRequest((Activity) this);
// don't use SSO.
op.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
// no callback needed.
op.setCallback(null);
// set permissions.
List<String> permissions = new ArrayList<String>();
permissions.add("email");
permissions.add("user_birthday");
op.setPermissions(permissions);
// open session for read.
currentSession.openForRead(op);
Logger.d(TAG, "Session open for read request issued.");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Logger.d(TAG, "Request code is: " + requestCode);
Logger.d(TAG, "Result code is: " + resultCode);
super.onActivityResult(requestCode, resultCode, data);
if (Session.getActiveSession() != null)
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
Session session = new Session.Builder(getApplicationContext()).build();
Session.setActiveSession(session);
currentSession = session;
}
if (currentSession.isOpened()) {
Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
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) {
if (user != null) {
Logger.i(TAG, "User:" + user.getInnerJSONObject());
}
}
});
}
}
});
}
}
I hope this helps.
When you are using Request.GraphUserCallback(), its best to use it in MAIN UI THREAD
Session s = Session.getActiveSession();
if(s!=null)
{
Request.executeMeRequestAsync(s,new Request.GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user, Response response)
{
if(user!=null)
{
try {
String fbid=null;
String birthday=null;
fbid=user.getId();
birthday=user.getBirthday();
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
});
}
you can try this also before the Request.executeMeRequestAsync(...){...}
List<String> permissions = session.getPermissions();
List<String> permissionsBirthday = new ArrayList<String>();
permissionsBirthday.add("user_birthday");
if (!isSubsetOf(permissionsBirthday, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, permissionsBirthday);
if (setPermissions(session, newPermissionsRequest))
return;
}
the method isSubsetOf();
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
hope this helps.
This code worked for me hope you find it useful. This retrieves the user email in 3 different ways and also logs it
try{
// new Read().execute("Facebook");
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// TextView welcome = (TextView) findViewById(R.id.welcome);
// welcome.setText("Hello " + user.getName() + "!");
Log.d("useremai", (String) user.getProperty("email"));
Log.d("USER", user.getInnerJSONObject().toString());
JSONObject details = user.getInnerJSONObject();
useremail = details.optString("email");
Log.d("name", user.getName());
Log.d("email", useremail);
}
}
});
}
}
});
}catch(NoClassDefFoundError e){
e.printStackTrace();
}
Try this one:
if you have object of user than do below:
if (user != null) {
String UserId = user.getId();
try {
Log.i("Birthdate", ""+user.getInnerJSONObject().getString("birthday"));
} catch (JSONException e) {
e.printStackTrace();
}
}

Getting email address by using Facebook SDK 3.0.1 for Android

I'm currently developing an application which aims to authenticate any user by using Facebook acoount.
I have a trouble in getting user email from user's account. My code is below
private void signInWithFacebook() {
SessionTracker mSessionTracker = new SessionTracker(getBaseContext(), new StatusCallback() {
public void call(Session session, SessionState state, Exception exception) {
}
}, null, false);
String applicationId = Utility.getMetadataApplicationId(getBaseContext());
Session mCurrentSession = mSessionTracker.getSession();
if (mCurrentSession == null || mCurrentSession.getState().isClosed()) {
mSessionTracker.setSession(null);
Session session = new Session.Builder(getBaseContext()).setApplicationId(applicationId).build();
Session.setActiveSession(session);
mCurrentSession = session;
}
if (!mCurrentSession.isOpened()) {
Session.OpenRequest openRequest = null;
openRequest = new Session.OpenRequest(FacebookLoginActivity.this);
if (openRequest != null) {
openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
openRequest.setPermissions(Arrays.asList("user_birthday", "email", "user_location"));
openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
mCurrentSession.openForRead(openRequest);
}
}else {
Request.executeMeRequestAsync(mCurrentSession, new Request.GraphUserCallback() {
public void onCompleted(GraphUser user, Response response) {
Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getLink() + " "+ response);
}
});
}
}
I am using Facebook SDK 3.0.1 for Android.
I have set the permissions required by the Facebook Graph Api.
In the response xml, there is no such field like email.
Facebook Sdk documentations are not good enough and I don't know hot to obtain email address.
Thanks in advance.
Email is not a default field that's returned. Instead, you should create a meRequest, and pass it a parameter like: fields=email.
Request me = Request.newMeRequest(mCurrentSession, new GraphRequestCallback() {...});
Bundle params = me.getParameters();
params.putString("fields", "email,name");
me.setParameters(params);
me.executeAsync();
you call just like this under regular things - only different you cannot directly user.email
System.out.println(user.asMap().get("email").toString());
regular :
#Override
public void onClick(View v) {
// start Facebook Login
Session.openActiveSession(Giris.this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
System.out.println(user.getName());
System.out.println(user.getBirthday());
System.out.println(user.getFirstName());
System.out.println(user.getLastName());
System.out.println(user.getLink());
System.out.println(user.getUsername());
System.out.println(user.getLocation());
System.out.println("facebook user id" + user.getId());
System.out.println(user.asMap().get("email").toString());
// Session.OpenRequest open = new Session.OpenRequest(Login)
}
}
});
}
}
});
}
just call this method will return user email id to you.
private void doSocialNetworkinWithFacebook()
{
// check for session
Session session=Session.getActiveSession();
if (session != null && session.isOpened())
{
// user is already login show
try
{
Session.OpenRequest request = new Session.OpenRequest(this);
request.setPermissions(Arrays.asList("email", "publish_actions"));
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Request.executeMeRequestAsync(session, new Request.GraphUserCallback()
{
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response)
{
if (user != null)
{
Toast.makeText(activity, "Welcome "+user.getName(), Toast.LENGTH_SHORT).show();
// publishFeedDialog(session);
try
{
strFirstName = user.getFirstName().toString();
strLocation = user.getLocation().getProperty("name").toString();
strEmail = user.asMap().get("email").toString();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
strEmail="";
}
runOnUiThread(new Runnable()
{
public void run()
{
setUserInfoFromFacebook(strFirstName, strLocation, strEmail);
}
});
}
}
});
}
else
{
// user is not log in
//show login screen
// start Facebook Login
try
{
Session.OpenRequest request = new Session.OpenRequest(this);
request.setPermissions(Arrays.asList("email", "publish_actions"));
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Session.openActiveSession(activity, true, new Session.StatusCallback()
{
// callback when session changes state
#Override
public void call(final Session session, SessionState state, Exception exception)
{
//session.openForRead(new Session.OpenRequest(this).setPermissions(Arrays.asList("email")));
Log.d(TAG, "Session :"+session.toString());
Log.d(TAG, "Session is opened :"+session.isOpened());
if (session.isOpened())
{
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback()
{
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response)
{
if (user != null)
{
Toast.makeText(activity, "Welcome "+user.getName(), Toast.LENGTH_SHORT).show();
// publishFeedDialog(session);
try
{
strFirstName = user.getFirstName().toString();
strLocation = user.getLocation().getProperty("name").toString();
strEmail = user.asMap().get("email").toString();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
strEmail="";
}
runOnUiThread(new Runnable()
{
public void run()
{
setUserInfoFromFacebook(strFirstName, strLocation, strEmail);
}
});
}
}
});
}
else if(session.isClosed())
{
Toast.makeText(activity, "Unable to connect facebook, please try later..",Toast.LENGTH_SHORT).show();
}
}
});
}
}
First add the appropriate permission, then fetch the email using the getProperty function.
permissions = Arrays.asList("email","languages","user_location","user_likes", "user_education_history","user_work_history","user_hometown","user_about_me","user_status");
Log.i(TAG, "user_email : " + user.getProperty("email"));

Categories

Resources