我正在尝试将facebook登录添加到Android应用程序中。虽然登录按钮和登录工作正常,但我也在尝试获取用户登录时的名字和姓氏。但是,String用户名始终保持为null。以下是此活动的完整代码:
public class FacebookLoginActivity extends BaseActivity {
private TextView info;
private LoginButton loginButton;
private CallbackManager callbackManager;
private String username;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.fb_login_activity);
info = (TextView) findViewById(R.id.info);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
setData();
if(username != null) {
Intent intent = new Intent(FacebookLoginActivity.this, LoginActivity.class);
Bundle bundle = new Bundle();
bundle.putString("username", username);
intent.putExtras(bundle);
startActivity(intent);
}
}
@Override
public void onCancel() {
info.setText("Login attempt canceled.");
}
@Override
public void onError(FacebookException error) {
info.setText("Login attempt failed.");
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private void setData(){
if(AccessToken.getCurrentAccessToken() != null){
final GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
if(AccessToken.getCurrentAccessToken()!=null){
try {
username = response.getJSONObject().getString("first_name")+ " " + response.getJSONObject().getString("last_name");
}
catch(JSONException e){
e.printStackTrace();
}
}
}
});
}
}
}