我正在尝试使用Facebook Graph API获取用户的个人资料。但有时我在GraphRequest响应中得到Profile对象值null,但JSONObject和GraphResponse都没问题。以下是我正在做的代码。
Facebook SDK的build.gradle中的依赖项:
compile 'com.facebook.android:facebook-android-sdk:4.16.0'
在我正在进行的活动中:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
facebookCallback();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.txt_login_facebook:
if (CommonUtils.isNetworkConnected(LoginActivity.this)) {
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "user_birthday", "email", "user_location"));
} else {
CommonUtils.showNoInternetAlert(LoginActivity.this, null);
}
break;
default:
break;
}
}
private AccessToken accessToken;
private CallbackManager callbackManager;
private void facebookCallback() {
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
accessToken = loginResult.getAccessToken();
getUserDataThroughGraphAPI();
Log.i("error", "success" + "");
}
@Override
public void onCancel() {
Log.e("Facebook-Login-Cancel", "Cancelled");
}
@Override
public void onError(FacebookException exception) {
Log.e("Facebook-Login-onError", exception.toString());
}
});
}
/**
* This method gives you data from Facebook through Graph API after successful login to Facebook.
* Use {@link #getUserDataThroughGraphAPI()}
*
* @return Nothing.
*/
private void getUserDataThroughGraphAPI() {
try {
GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject jsonobject, GraphResponse response) {
Profile profile = Profile.getCurrentProfile();
Log.e("Facebook json", jsonobject.toString());//Getting Correctly
Log.e("Facebook graph", response.toString());//Getting correctly
Log.e("Facebook profile", profile+"");//Getting Profile Object null sometimes
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,email,gender,birthday,location");
request.setParameters(parameters);
request.executeAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
任何帮助都会受到关注:)