Cannot retrieve data from Facebook SDK - android

Any idea, why I cannot get email from Facebook? I got error like - No value for "email" or sth like that.
private void fbInit() {
// Initialize the SDK before executing any other operations,
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
callbackManager = CallbackManager.Factory.create();
// get new instance of fb
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
loginResult.getAccessToken().getUserId();
getFbData(loginResult.getAccessToken().getUserId());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
// access token tracker init
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(
AccessToken oldAccessToken,
AccessToken currentAccessToken) {
// Set the access token using
// currentAccessToken when it's loaded or set.
accessToken = currentAccessToken;
updateWithToken(currentAccessToken);
}
};
// If the access token is available already assign it.
accessToken = AccessToken.getCurrentAccessToken();
updateWithToken(accessToken);
// is this need?!
// profileTracker = new ProfileTracker() {
// #Override
// protected void onCurrentProfileChanged(
// Profile oldProfile,
// Profile currentProfile) {
// // App code
// }
// };
}
private void updateWithToken(AccessToken currentAccessToken) {
// this way I check if there is email permission which is needed to register/login
if (currentAccessToken != null
&& !currentAccessToken.getDeclinedPermissions().contains("email")
&& !currentAccessToken.getDeclinedPermissions().contains("basic_info")) {
// go to other activity (?)
} else {
ActivityUtils.showToast(this, "no email permission");
}
}
private void getFbPermissions() {
Collection<String> permissions = Arrays.asList("public_profile", "email", "user_photos", "user_birthday");
LoginManager.getInstance().logInWithReadPermissions(this, permissions);
}
private void getFbData(String userId) {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
if (response != null) {
try {
Log.i("LoginActivityFbResponse", response.toString());
ActivityUtils.showToast(getActivity(),
object.getString("id") + object.getString("name") + object.getString("email")
+ object.getJSONArray("location").getString(1) + object.getString("locale")
+ object.getString("birthday") + object.getString("gender"));
// TODO: try to login
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email");
request.setParameters(parameters);
request.executeAsync();
}
BTW. I want to get from Facebook at least this data: email, id, gender, birthday, location_name.

You get Error with birthday because you dont have permission of birthday in your GraphRequest.
Use it like :
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday,picture.type(large)");
request.setParameters(parameters);
request.executeAsync();
Can you try this and come with result ?

Related

Cannot get email from facebook Graph api

I implemented Facebook in app and fetched name,email and id from graph api,Now i cannot get email it from graph api and i passed id,name,email fields but got only id,name but not email.Is it change any privacy policy from facebook.
I'm Using https://graph.facebook.com/me?access_token=(token here)&fields=id,name,email
Try With This Running successfully
private void facebookLogin() {
mFaceBookloginButton = (LoginButton) findViewById(R.id.login_button);
mFaceBookloginButton.setReadPermissions("public_profile");
mFaceBookloginButton.setReadPermissions("email");
callbackManager = CallbackManager.Factory.create();
mFaceBookloginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
MyLog.debug("Name" + loginResult.getAccessToken(), ActivityLogin.class);
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
MyLog.debug("Pic Url" + profile.getProfilePictureUri(200, 200), ActivityLogin.class);
MyLog.debug("User Name" + profile.getFirstName(), ActivityLogin.class);
MyLog.debug("User Email" + profile.getLastName(), ActivityLogin.class);
}
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
FacebookUser facebookUser = null;
try {
if (object != null) {
facebookUser = new FacebookUser();
if (object.has("id")) {
facebookUser.setId(object.getString("id"));
}
if (object.has("first_name")) {
facebookUser.setFirst_name(object.getString("first_name"));
}
if (object.has("last_name"))
facebookUser.setLast_name(object.getString("last_name"));
if (object.has("email"))
facebookUser.setEmail(object.getString("email"));
}
if (facebookUser != null) {
hitSocialLogin(facebookUser);
LoginManager.getInstance().logOut();
}
} catch (Exception e) {
MyLog.printException(e);
} finally {
LoginManager.getInstance().logOut();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name, email,gender, birthday, location"); // Parámetros que pedimos a facebook
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
MyLog.debug("on Cancel", ActivityLogin.class);
}
#Override
public void onError(FacebookException exception) {
MyLog.debug("on Cancel" + exception, ActivityLogin.class);
}
});
}

Profile.getCurrentProfile() return only my profile, all the rest are null

I'm trying to build a simple login to facebook app (with FB api v4.0)and retrieve some data about the user, but for some reason I success to login and get data only from my personal facebook profile, if tried to login with other users profile I'm getting null. (I change the setting in facebook developer to public app).
this is some of my loginButton_Fragment:
private CallbackManager callbackManager;
private FacebookCallback<LoginResult> facebookCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
Log.d("koko",accessToken.toString() );
if (profile != null){
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
user_birthDay = object.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,birthday");
request.setParameters(parameters);
request.executeAsync();
user_name = profile.getName();
user_id = profile.getId();
Log.d("koko","first " +user_name + " " + user_id + " " + user_birthDay );
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
comm.respone(user_name, user_id, user_birthDay);
}
}, 500);
}
}
#Override
public void onCancel () {
}
#Override
public void onError (FacebookException e){
}
};
Each time I login, I'm getting inside the onSuccess, but if its not my personal profile so the profile its null.
set read permissions mButtonLogin.setReadPermissions(Arrays.asList("email,public_profile","user_birthday"));
try like this
mButtonLogin.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d("status", "onSuccess");
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
try {
String name = object.getString("name");
String email =object.getString("email");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name,email,birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.d("status", "onCancel");
}
#Override
public void onError(FacebookException e) {
Log.d("status", "onError " + e);
}
}
);
You need to acquire app specific permission from Facebook for retrieve user personal information's such as birthday, user_friends etc by submitting it for a review.
Invest few moments here .
If your app requests such permissions Facebook will have to review how your app uses it.
You will get public_profile as it's default .
Check this & this .

Facebook Profile.getCurrentProfile() is always returns null after the first login

For the first time when I login into the app through Facebook, I'm getting profile from Profile.getCurrentProfile();
Where as when I exit the app and launch again, It was already logged in. So I can call directly Profile.getCurrentProfile(); is returning null.
Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_page);
Profile profile = Profile.getCurrentProfile();
// For the first launch the profile will be null
displayProfileName(profile);
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile");
callbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(
Profile oldProfile, Profile currentProfile) {
profileTracker.stopTracking();
Profile.setCurrentProfile(currentProfile);
Profile profile = Profile.getCurrentProfile();
displayProfileName(profile);
}
};
profileTracker.startTracking();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if (profileTracker != null) {
profileTracker.stopTracking();
}
}
#Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
#Override
protected void onRestart() {
super.onRestart();
AppEventsLogger.activateApp(this);
}
/**
*
* Method to display the Profile Name
*/
private void displayProfileName(Profile profile) {
if (profile != null) {
Toast.makeText(MainActivity.this, profile.getName(),
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "No Profile", Toast.LENGTH_LONG)
.show();
}
}
#Override
protected void onActivityResult(int arg0, int arg1, Intent arg2) {
super.onActivityResult(arg0, arg1, arg2);
callbackManager.onActivityResult(arg0, arg1, arg2);
}
There are two cases in this:
For first login, follow my other answer.
For second login, you will need to refresh your AccessToken and then fetch the profile. Refreshing token code can be found in this answer but the code below has it (for simplification).
The code is taken from FB's dreadful documentation).
You can put this code straight into your app, where the comment says "case 1", just invoke your normal FB login.
private AccessTokenTracker mAccessTokenTracker;
private void loginToMyFbApp() {
FacebookSdk.sdkInitialize(this);
if (AccessToken.getCurrentAccessToken() != null) {
mAccessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
mAccessTokenTracker.stopTracking();
if(currentAccessToken == null) {
//(the user has revoked your permissions -
//by going to his settings and deleted your app)
//do the simple login to FaceBook
//case 1
}
else {
//you've got the new access token now.
//AccessToken.getToken() could be same for both
//parameters but you should only use "currentAccessToken"
//case 2
fetchProfile();
}
}
};
mAccessTokenTracker.startTracking();
AccessToken.refreshCurrentAccessTokenAsync();
}
else {
//do the simple login to FaceBook
//case 1
}
}
private void fetchProfile() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// this is where you should have the profile
Log.v("fetched info", object.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link"); //write the fields you need
request.setParameters(parameters);
request.executeAsync();
}
Instead of accessing Profile.getCurrentProfile()
use access token and make graph request in onSuccess()
( It worked for me)
here snippet of code :
FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.v("profile track", (DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(loginResult.getAccessToken().getExpires())));
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String name = object.getString("name");
String email = object.getString("email");
String id = object.getString("id");
Toast.makeText(Login.this, name + " " + " " + email + " " + id, Toast.LENGTH_SHORT).show();
/*write your code that is to be executed after successful login*/
} catch (JSONException ex) {
ex.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
Call LoginManager.getInstance().logOut(); once you get the profile details.

How to add a logout callback for facebook sdk in android

I have integrated Facebook sdk in my android app. As described in the manual I added the login callback for facebook. But I have to change the UI if the user logs out from facebook. Where do I put that code. My code for login is
/**
* Login Callback for facebook login
*/
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
//Call updateUI()
setData("provider","facebook");
loginType = LoginTypes.FB_LOGIN;
isLoggedin = true;
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
txtName.setText(response.toString());
updateUI();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
editText_message.setText("Login Cancelled.");
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
there are 2 possible ways:
1) you need to overwrite in on create AccessTokenTracker like this:
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken,
AccessToken currentAccessToken) {
if (currentAccessToken == null) {
//write your code here what to do when user logout
}
}
}
2) You can call LoginManager.logOut() to log out the user
hope this will help you :)
Thank you Stan. You helped me solve, but took me some time. To help other people, that's whole code:
Profile fbProfile = Profile.getCurrentProfile();
AccessTokenTracker accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken,
AccessToken currentAccessToken) {
if (currentAccessToken == null) {
Log.d(TAG, "onLogout catched");
deleteContact();//This is my code
}
}
};
if (fbProfile == null) {
Log.d(TAG, "NOT logged in");
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("email");
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "onSuccess login Facebook");
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
FacebookSdk.setIsDebugEnabled(true);
FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Log.d(TAG, "AccessToken.getCurrentAccessToken() " + AccessToken.getCurrentAccessToken().toString());
Profile profile = Profile.getCurrentProfile();
Log.d(TAG, "Current profile: " + profile);
if (profile != null) {
Log.d(TAG, String.format("id = %s; name = %s; lastName = %s; uri = %s",
profile.getId(), profile.getFirstName(),
profile.getLastName(), profile.getProfilePictureUri(50, 60)));
name = String.format("%s %s",profile.getFirstName(),profile.getLastName());
fbid = profile.getId();
pushNewContact();//This is my code
}
}
});
request.executeAsync();
}
#Override
public void onCancel() {
Log.d(TAG, "onCancel");
}
#Override
public void onError(FacebookException e) {
Log.e(TAG, "onError", e);
}
});
} else {
Log.d(TAG, "Logged with " + fbProfile.getName());
fbid = fbProfile.getId();
}
accessTokenTracker.startTracking();
This worked for me:-
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(
Profile oldProfile,
Profile currentProfile) {
if(currentProfile == null){
tvUNameandEmail.setText(R.string.app_name);
}
}
};

Get profile data from Facebook SDK on Android always return Null. Why?

i just learned about facebook SDK on android. I already search on stackoverflow and facebook developer guide for login, but i still stuck when get profile data from facebook sdk. i try implement solution from : unable get profile and Get email, but still stuck.
There is my code :
public class HomeLoginActivity extends Activity {
LoginButton btnFacebook;
CallbackManager callbackManager = CallbackManager.Factory.create();
ProfileTracker profTrack;
AccessTokenTracker accessTokenTracker;
TextView welcomeText;
FacebookCallback<LoginResult> mFacebookCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
setContentView(R.layout.activity_home_login);
welcomeText = (TextView) findViewById(R.id.welcome_id);
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(
AccessToken oldAccessToken,
AccessToken currentAccessToken) {
// App code
Log.d("current token", "" + currentAccessToken);
//}
}
};
profTrack = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(
Profile oldProfile,
Profile currentProfile) {
// App code
Log.d("current profile", "" + currentProfile);
welcomeText.setText(constructWelcomeMessage(currentProfile));
}
};
mFacebookCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
welcomeText.setText(constructWelcomeMessage(profile));
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
try {
String id=object.getString("id");
String name=object.getString("name");
String email=object.getString("email");
String gender=object.getString("gender");
Stringbirthday=object.getString("birthday");
//do something with the data here
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
accessTokenTracker.startTracking();
profTrack.startTracking();
//Button Facebook
btnFacebook = (LoginButton) findViewById(R.id.btnFacebook);
btnFacebook.setReadPermissions("public_profile", "user_friends");
btnFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions((Activity) v.getContext(),Arrays.asList("public_profile", "user_friends"));
}
});
btnFacebook.registerCallback(callbackManager, mFacebookCallback);
}
// ennd on create
private String constructWelcomeMessage(Profile profile) {
StringBuffer stringBuffer = new StringBuffer();
if (profile != null) {
stringBuffer.append("Welcome " + profile.getName());
}
else {
stringBuffer.append("NULL Profile");
}
return stringBuffer.toString();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onResume() {
super.onResume();
AccessToken.getCurrentAccessToken();
Log.d("resume current token", "" + AccessToken.getCurrentAccessToken());
Profile.fetchProfileForCurrentAccessToken();
}
#Override
public void onStop() {
super.onStop();
profTrack.stopTracking();
accessTokenTracker.stopTracking();
}
#Override
public void onDestroy() {
super.onDestroy();
accessTokenTracker.stopTracking();
profTrack.stopTracking();
}
}
and there is my log cat :
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
at com.twiscode.gimme.HomeLoginActivity$3$1.onCompleted(HomeLoginActivity.java:100)
at com.facebook.GraphRequest$1.onCompleted(GraphRequest.java:298)
at com.facebook.GraphRequest$5.run(GraphRequest.java:1246)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Try this sample code to get profile info
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
// login ok get access token
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
if (BuildConfig.DEBUG) {
FacebookSdk.setIsDebugEnabled(true);
FacebookSdk
.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
System.out
.println("AccessToken.getCurrentAccessToken()"
+ AccessToken
.getCurrentAccessToken()
.toString());
Profile.getCurrentProfile().getId();
Profile.getCurrentProfile().getFirstName();
Profile.getCurrentProfile().getLastName();
Profile.getCurrentProfile().getProfilePictureUri(50, 50);
//String email=UserManager.asMap().get(“email”).toString();
}
}
});
request.executeAsync();
/* Bundle parameters = new Bundle();
parameters
.putString("fields",
"id,firstName,lastName,name,email,gender,birthday,address");
request.setParameters(parameters);
Intent loginintent = new Intent(getActivity(),
EditProfile.class);
startActivity(loginintent);
System.out.println("XXXX " + getId());
*/
makeJsonObjReq();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
return view;
I was facing the same error and finally found the solution. Basically you have to know first what is causing this crash/NullPointerException. So to find out what is causing this exception, make your onComplete block of code look like below:
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Log.v("LoginActivity Response ", response.toString());
}
});
Now, run your app and try logging in using the FB button. Keep checking your logcat and soon you will see a line like below:
V/LoginActivity Response: {Response: responseCode: 200, graphObject: {"id":"10206735777938523","name":"Rohit Paniker","email":"rohit.paniker.1990#gmail.com","gender":"male"}, error: null}
I was using the "age" permission which was causing the NullPointerException in ID, Name, Email and all permissions which i got to know from the above logcat output. As per the output i understood why the crash was happening and I removed the object.getString("age") and ran the app again, worked perfectly without crash and I got all data from ID to Name and email!
See my working code below to get profile details FB SDK 4
//Initialize Facebook SDK
FacebookSdk.sdkInitialize(getApplicationContext());
//if the facebook profile is changed, below code block will be called
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
if(currentProfile != null){
fbUserId = currentProfile.getId();
if(!sharedPreferences.contains("UserName")){
editor.putString("UserName",currentProfile.getFirstName()+" "+currentProfile.getLastName());
}
if(!sharedPreferences.contains("FbId")){
editor.putString("FbId",currentProfile.getId());
}
if(!sharedPreferences.contains("ProfilePicture")){
editor.putString("ProfilePicture",currentProfile.getProfilePictureUri(100,100).toString());
}
editor.commit();
}
}
};
//when new fb user logged in , below code block will be called
AccessTokenTracker accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken accessToken, AccessToken accessToken2) {
System.out.println("acesstoken trackercalled");
}
};
//set layout resource
setContentView(R.layout.activity_login);
//fb login button
loginButton = (LoginButton) findViewById(R.id.connectWithFbButton);
//set fb permissions
loginButton.setReadPermissions(Arrays.asList("public_profile,email"));
//call the login callback manager
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
profile = Profile.getCurrentProfile();
if(profile != null){
fbUserId = profile.getId();
if(!sharedPreferences.contains("UserName")){
editor.putString("UserName",profile.getFirstName()+" "+profile.getLastName());
}
if(!sharedPreferences.contains("FbId")){
editor.putString("FbId",profile.getId());
}
if(!sharedPreferences.contains("ProfilePicture")){
editor.putString("ProfilePicture",profile.getProfilePictureUri(20,20).toString());
}
editor.commit();
}
goToNewActivity();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
});
Please try with this code :
LoginManager.getInstance().logInWithReadPermissions(Activity.this,
Arrays.asList("public_profile","email"));
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
public void onSuccess(LoginResult loginResult) {
if (AccessToken.getCurrentAccessToken() != null) {
Log.e("idfb",""+loginResult.getAccessToken().getUserId());
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Application code
try {
Log.i("Response",response.toString());
String email = response.getJSONObject().getString("email");
String name = response.getJSONObject().getString("name");
String id = response.getJSONObject().getString("id");
String imgUrl = "https://graph.facebook.com/" + id + "/picture?type=large";
Log.i("Login" + "Email", "");
Log.i("Login"+ "FirstName", name);
Log.i("Login" + "Id", id);
} catch (JSONException e) {
e.printStackTrace();
Log.e("errorfb",""+e);
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,email,name,link");
request.setParameters(parameters);
request.executeAsync();
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
});

Categories

Resources