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();
}
}
Related
I am creating an Android App that fetches Facebook timeline posts of the logged in user. I using Facebook SDK for Android 4.27.0
My Problem
Now the problem is , after the graph request executed , the graph request return error messages with null content . (But Graph Request to retrive profile info is success).
So tried two types of methods that initiates Graph Request
GraphRequest.newMeRequest ()
new GraphRequest(.....)
Both are returning error messages .
Tried accessing non-existing field (Message) on node type (user)
{data:[]}
My Code ::
public class MainActivity extends AppCompatActivity {
String email="===",name="====";
TextView txtstatus,txt3;
LoginButton login_button;
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FacebookSdk.sdkInitialize(getApplicationContext());
intializeControls();
LoginWithFB();
}
private void intializeControls()
{
callbackManager = CallbackManager.Factory.create();
txtstatus = (TextView) findViewById(R.id.textView);
login_button = (LoginButton) findViewById(R.id.login_button);
login_button.setReadPermissions(Arrays.asList(
"public_profile", "email", "user_birthday", "user_friends","user_posts", "user_status")); // Setting permissions
}
void LoginWithFB ()
{
login_button.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
final Profile profile = Profile.getCurrentProfile();
txtstatus.setText("Login Success" );
GraphRequest request = GraphRequest.newMeRequest( //To read profile Info
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
TextView txt2 = (TextView) findViewById(R.id.textView2);
TextView nametext = (TextView) findViewById(R.id.nameText);
txt3 = (TextView) findViewById(R.id.textView3);
// Application code
name = object.getString("name");
email = object.getString("email");
nametext.setText(name);
txt2.setText(email);
} catch (Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
//Now graph Query to read timeline posts
Bundle params = new Bundle();
params.putString("fields", "message,created_time,id,full_picture,status_type,source,comments.summary(true),likes.summary(true)");
params.putString("limit", "10");
/* make the API call */
//Method - 1
GraphRequest requestPost = GraphRequest.newMeRequest( //To read profile Info
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
txt3.setText(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
requestPost.setParameters(params);
requestPost.executeAsync();
//Method - 2
new GraphRequest( loginResult.getAccessToken(), "/me/posts", params, HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
TextView postsText = (TextView) findViewById(R.id.postText);
postsText.setText(response.toString());
}
}
).executeAsync();
}
#Override
public void onCancel() {
txtstatus.setText("Login canceled");
}
#Override
public void onError(FacebookException error) {
txtstatus.setText("Login failed"+error.getMessage());
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
The Output::
=This the error I got
My steps to resolve :
I used the Method 2 first , but it returned data::null , so I tried the Method-1 , it also returned error message only.
But both error messages are different . Since I am new to Facebook SDK , I can't resolve on my own.
Please guide me to resolve this error.
I want to retrieve logged in user email. This is what I tied, but not retrieving the email. I could retrieve only id, first name, last name but not the email
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("LoginActivity", response.toString());
// Application code
try {
String userEmail = object.getString("email");
String userId = object.getString("id");
emailEditText.setText(userEmail);
new SignupTask(SignupActivity.this, userId, userEmail).execute();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name, email"); // Parámetros que pedimos a facebook
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
});
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email", "user_friends"));
What do I have missed....
ohk..try this code its working for me...
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setBackgroundResource(R.drawable.fb);
loginButton.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
loginButton.setReadPermissions(Collections.singletonList("public_profile, email, user_birthday, user_friends"));
callbackManager = CallbackManager.Factory.create();
if (netWorkStatus) {
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
//Store Facebook data to webservice .
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Application code
try {
// String picture = object.getString("picture");
//JSONObject jobj = new JSONObject(picture);
//JSONObject dataObj = jobj.getJSONObject("data");
name = object.getString("name");
userEmail = object.getString("email");
//String url = dataObj.getString("url").replace("\\", "");
} catch (Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday,picture");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
CallbackManager callbackManager ;
//in OnCreate initialize it
callbackManager = CallbackManager.Factory.create();
//after that overide onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
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 .
How to get email id from facebook Login
permission added are
mFBLoginButton.setReadPermissions("user_friends");
mFBLoginButton.setReadPermissions("public_profile");
mFBLoginButton.setReadPermissions("email");
mFBLoginButton.setReadPermissions("user_birthday");
I am going through Facebook tutorial for login and to access email I am using GraphRequest code is as below
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/me?fields=email",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
if (response != null)
Log.d(TAG, " response " + response.toString());
}
}
).executeAsync();
but I am not getting email in the response.
could some one help me please
you need to asking for the permissions` using the parameter while logging in to grab permissions, you must also consider the fact that not every logged in user has an email assigned to their account also permissions to access it.
one can open and verify their facebook accounts using their Mobile numbers, hence the probability that no email exists in your account.
hope this info helps!
As 'Md Abdul Gafur' mentioned make sure your facebook account is properly setup.
Add the dependency to your build.gradle:
compile 'com.facebook.android:facebook-android-sdk:4.2.0'
Add the facebook activity to your AndroidManifest.xml:
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
Then in your actvitiy override onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
Login from your activity with:
FacebookSdk.sdkInitialize(mContext.getApplicationContext());
FacebookSdk.setApplicationId(mApiKey);
mCallbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse response) {
if (response.getError() != null) {
// handle error
} else {
if (user != null) {
// Get the data you need
String email = user.optString("email", "");
} else {
//handle null user
}
}
}
});
request.executeAsync();
}
#Override
public void onCancel() {
//handle cancel
}
#Override
public void onError(FacebookException exception) {
// handle exception
}
});
LoginManager.getInstance().logInWithReadPermissions(mContext, Collections.singletonList("public_profile"));
Use this code. it's works successfully. You can get all user data by this.
loginButton = (LoginButton) findViewById(R.id.login_button);
List < String > permissionNeeds = Arrays.asList("user_photos", "email",
"user_birthday", "public_profile", "AccessToken");
loginButton.registerCallback(callbackManager,
new FacebookCallback < LoginResult > () {#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("onSuccess");
String accessToken = loginResult.getAccessToken()
.getToken();
Log.i("accessToken", accessToken);
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
Log.i("LoginActivity", response.toString());
try {
id = object.getString("id");
try {
URL profile_pic = new URL(
"http://graph.facebook.com/" + id + "/picture?type=large");
Log.i("profile_pic",
profile_pic + "");
} catch (MalformedURLException e) {
e.printStackTrace();
}
name = object.getString("name");
email = object.getString("email");
gender = object.getString("gender");
birthday = object.getString("birthday");
} 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() {
System.out.println("onCancel");
}
#Override
public void onError(FacebookException exception) {
System.out.println("onError");
Log.v("LoginActivity", exception.getCause().toString());
}
});
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) {
}
});