newMeRequest's onCompleted method user is always null - android

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);

Related

Facebook android SDK4.0 get mail address

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.

Facebook getName()

I did the following to try and get the user's name using Facebook's Graph API. I have the login button working but the user always appears to be null onCompleted(..)
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in..." + session.toString());
// Request user data and show the results
Request.newMeRequest(session, new Request.GraphUserCallback() {
public void onCompleted(GraphUser user, Response response) {
if (user == null)
{
Log.i("", "no!");
}
else {
Log.i("", "YES " + user.getName());
}
}
}
).executeAsync();
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
Found the solution...
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
of course...

how to get user email address using Parse Facebook for Android-

I am trying to get email address of user from ParseFacebook for android but i am getting null when i try to fetch email.
here is my code
//on Login:
List<String> permissions = Arrays.asList("email","basic_info", "user_about_me", "user_location");
ParseFacebookUtils.logIn(permissions,SignUpActivity. this, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
SignUpActivity.this.progressDialog.dismiss();
if(err!=null)
Log.w("parse exception",""+err.getMessage());
if (user == null) {
Log.e("FB","Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.w("FB","User signed up and logged in through Facebook!");
//showUserDetailsActivity();
getProfileInfo();
} else {
Log.w("FB","User logged in through Facebook!");
// showUserDetailsActivity();
getProfileInfo();
}
}
});
making request:
Request request = Request.newMeRequest(ParseFacebookUtils.getSession(),new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
JSONObject userProfile = new JSONObject();
try {
// Populate the JSON object
try {
userProfile.put("facebookId", user.getId());
userProfile.put("name", user.getName());
} catch (Exception e) {
// TODO: handle exception
}
if (user.getProperty("email") != null) {
userProfile.put("email",(String) user.getProperty("email"));
}
if (user.getLocation().getProperty("name") != null) {
userProfile.put("location", (String) user.getLocation().getProperty("name"));
}
if (user.getProperty("gender") != null) {
userProfile.put("gender",(String) user.getProperty("gender"));
}
} catch (JSONException e) {
Log.e("Facebook parsing data","Error parsing returned user data.");
}
} else if (response.getError() != null) {
if ((response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_RETRY) || (response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_REOPEN_SESSION)) {
Log.e("Facebook parsing data","The facebook session was invalidated.");
//onLogoutButtonClicked();
} else {
Log.e("Facebook parsing data","Some other error: "+ response.getError().getErrorMessage());
}
}
}
});
request.executeAsync();
I have tried everything but where ever i do i am getting email null :(
After setting the permissions as above access the email via: user.asMap().get("email"));
You should get the email like this
String email = (String) response.getGraphObject().getProperty("email");
if(email!=null && !email.equals("")
//email variable should've email id.
Try removing the permission list in the login call.
ParseFacebookUtils.logIn(SignUpActivity.this, new LogInCallback() {
//you can add permissions on later screens.
}
Please add you this request:
Request request = Request.newMeRequest(ParseFacebookUtils.getSession(),new Request.GraphUserCallback()
In login request condition => user.isnew()
else if (user.isNew()) {
Log.w("FB","User signed up and logged in through Facebook!");
//showUserDetailsActivity();
getProfileInfo();
}
write your block in between this and you will be able to get new user info with email also.
This perfectly works in iOS and sure will help in android.
Before the line
request.executeAsync();
add these three lines.
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email");
request.setParameters(parameters);
Now you will get email in your response

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

Facebook android SDK 3 get email from user

Here is my code for facebook me request.i want to get user email and other basic info.this code is work without any issue in emulator.but in real device email gives null value. id,fristname... comes with real values. how can i get email on real device?
Request request = Request.newMeRequest(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
RequestParams params = new RequestParams();
params.put("email",(String) user.getProperty("email"));
params.put("password", "");
params.put("facebook_id", user.getId());
editor.putString("facebook_id", user.getId());
login(params,
(String) user.asMap().get("email"),
user.getId(), user.getFirstName(),
user.getLastName());
}
}
});
Bundle params = new Bundle();
params.putString("fields", "id,email,first_name,last_name");
request.setParameters(params);
request.executeAsync();
Instead of submitting a ME request, use Facebook's LoginButton, and add a hook to intercept the user info:
// Intercept the facebook user returned from login
facebookLoginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
mFacebookUser = user;
if (user != null) {
LogUtils.LOGFB(TAG, "Got a Facebook user: " + user.getFirstName() +
" " + user.getLastName() + ", email: " + user.getProperty("email"));
}
else {
LogUtils.LOGFB(TAG, "No Facebook user");
}
}
});
Then add an extra permission to get email:
facebookLoginButton.setReadPermissions(Arrays.asList(
"email", "user_birthday", ...));

Categories

Resources