当要求用户通过Facebook登录登录我的应用程序时,我想检索他们的电子邮件和名称,以便他们为我们的应用程序创建自定义帐户。但是,在要求他们通过Facebook登录并授权我们的应用程序获取用户姓名和电子邮件后,该应用程序不会转换到注册片段并将信息输入到电子邮件和名称字段中。
在LoginFragment中,我有这段代码专门用于检索用户的电子邮件和姓名。
mFaceLogin = (LoginButton) v.findViewById(R.id.login_button);
mFaceLogin.setReadPermissions(Arrays.asList("email", "public_profile"));
mFaceLogin.setFragment(this);
mFaceLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
final AccessToken accessToken = loginResult.getAccessToken();
GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
if (graphResponse.getError() == null) {
((MyRegisterListener) getActivity()).myStartRegisterFacebook(user.optString("first_name"), user.optString("email"));
}
}
});
}
@Override
public void onCancel() {
Toast.makeText(getActivity(), "fail", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(FacebookException error) {
Toast.makeText(getActivity(), "error", Toast.LENGTH_SHORT).show();
}
});
myStartRegisterFacebook方法假设调用Activity以切换到RegisterFragment并将名称和电子邮件发送到RegisterFragment的xml布局中显示的EditText字段。
LoginActivity
@Override
public void myStartRegisterFacebook(String name, String email) {
RegisterFragment registerFragment = new RegisterFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.lr_container,
new RegisterFragment()).addToBackStack(null).commit();
registerFragment.updateInformation(name, email);
}
RegisterFragment
public void updateInformation(String name, String email) {
mFname.setText(name);
mEmail.setText(email);
}
答案 0 :(得分:0)
尝试替换此行:
if (graphResponse.getError() == null) {
((MyRegisterListener) getActivity()).myStartRegisterFacebook(user.optString("first_name"), user.optString("email"));
}
这一行:
if (graphResponse != null) {
JSONObject obj = graphResponse.getJSONObject();
try {
((MyRegisterListener) getActivity()).myStartRegisterFacebook(obj.getString("first_name"), obj.getString("email"));
} catch (JSONException e) {
Log.e("JSONError:", e.toString());
}
}
答案 1 :(得分:0)
您可以使用GraphAPI获取电子邮件&amp;名称
GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject me, GraphResponse response) {
if (response.getError() != null) {
// handle error
} else {
String email = me.optString("email");
String id = me.optString("id");
final String userName =me.optString("name");
}
}
}).executeAsync();