Android Facebook登录 - 个人资料为空

时间:2015-12-14 06:05:52

标签: android facebook facebook-login

尝试在Android应用中集成Facebook登录。登录和注销工作正常,但有时甚至在登录后,配置文件仍为空。一旦我从Facebook获得详细信息,我就会退出。我在Stackoverflow上提到了一些其他的问题,并将它应用于代码中,但某些地方仍然存在问题并且无法解决问题。

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.login_activity);
    callbackManager = CallbackManager.Factory.create();
    loginButton = (LoginButton) findViewById(R.id.btnFacebookSignin);
    loginButton.setReadPermissions("public_profile, email");
    loginButton.registerCallback(callbackManager, facebookCallback);
}

FacebookCallback<LoginResult> facebookCallback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {

            if(Profile.getCurrentProfile() == null) {
                mProfileTracker = new ProfileTracker() {
                    @Override
                    protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
                        Log.v("facebook - profile", profile2.getFirstName());
                        mProfileTracker.stopTracking();
                    }
                };
                mProfileTracker.startTracking();
            }
            else {
                Profile profile = Profile.getCurrentProfile();
                Log.v("facebook - profile", profile.getFirstName());
            }
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {

                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {

                            if (BuildConfig.DEBUG) {
                                FacebookSdk.setIsDebugEnabled(true);
                                FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

                                Profile profile = Profile.getCurrentProfile();
                                if (profile != null) {

                                    String name = profile.getName();
                                    Uri pictureUri = profile.getProfilePictureUri(200, 200);
                                    String email = object.optString("email");
                                    String uid = object.optString("id");
                                    try {
                                        sendLogin(uid, name, email, pictureUri.toString(), "fb");
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    facebookLogout();
                                } else {
                                    facebookLogout();
                                    Toast.makeText(getApplication(), "Something went wrong, please try again later", Toast.LENGTH_LONG).show();
                                }
                            }
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "email");
            request.setParameters(parameters);
            request.executeAsync();
        }

        @Override
        public void onCancel() {
        }

        @Override
        public void onError(FacebookException e) {
            Toast.makeText(getApplication(), "Something went wrong, please try again later", Toast.LENGTH_LONG).show();
        }
    };

    public void facebookLogout() {
        LoginManager.getInstance().logOut();
    }

2 个答案:

答案 0 :(得分:1)

尝试此代码我希望它的工作..

   facebookimage(object.getString("id"));

这是方法:

 private void facebookimage(String id) {
        new getFacebookImage(id).execute();
    }

AsyncTask课程可在Facebook上获取个人资料图片;

private class getFacebookImage extends AsyncTask {

        String userID;
        Bitmap camera;

        public getFacebookImage(String id) {
            userID=id;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Object doInBackground(Object[] params) {


            URL imageURL = null;
            Bitmap bitmap=null;
            try {
                imageURL = new URL("https://graph.facebook.com/" + userID + "/picture?type=large");
                bitmap = BitmapFactory.decodeStream(imageURL.openConnection().getInputStream());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.e("String Image",""+bitmap);
            camera=bitmap;
            return bitmap;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);

            if(camera != null){
                Log.e("Image Load","UPload image");
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                camera.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                byte imageInByte[] = stream.toByteArray();
                String encodedImage = Base64.encodeToString(imageInByte, Base64.DEFAULT);
                DataBase.setUserImage(LoginActivity.this,encodedImage);

            }

        }
    }

答案 1 :(得分:0)

最初我只在onCompleted的JSONObject对象中获取id和email。即使我设置了像“public_profile”和“email”这样的权限,足以从facebook获取id,姓名,电子邮件和个人资料图片。但在某个地方我出错并且不理解并添加了Profile并且做了getProfile()所以我可以获得名称和个人资料图片。然后出现了其他问题,即使在登录完美之后,我有时会得到空的配置文件(可能是5次一次)。因为必须放置Profile Tracker,这是因为Profile异步工作(对我来说太混乱了,因为你必须放置跟踪器并开始和停止跟踪)。

然后我意识到我哪里出错了。在我们需要在json对象中提及我们想要的内容作为回复的包中,我只提到了“id”。所以现在在下面的代码中我添加了“name”和“email”。所以在JSONObject对象响应中我也得到了名称和电子邮件。

对于个人资料图片,我看到How can I display the users profile pic using the facebook graph api?并使用Uri构建器Use URI builder in Android or create URL with variables实现了这一点。因此,我完全删除了Profile的使用,仍然获得了我想要的所有数据。

这个答案是Destro - Android Facebook Login- Profile is null&amp;提到的两个答案的混合。 How to get email id From Android Facebook SDK 4.6.0?

FacebookCallback<LoginResult> facebookCallback = new FacebookCallback<LoginResult>() {

        @Override
        public void onSuccess(final LoginResult loginResult) {


            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {

                            if (BuildConfig.DEBUG) {
                                FacebookSdk.setIsDebugEnabled(true);
                                FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);


                                String uid = object.optString("id");
                                String email = object.optString("email");
                                String name = object.optString("name");

                                Uri.Builder builder = new Uri.Builder();
                                builder.scheme("https")
                                        .authority("graph.facebook.com")
                                        .appendPath(uid)
                                        .appendPath("picture")
                                        .appendQueryParameter("width", "1000")
                                        .appendQueryParameter("height", "1000");

                                Uri pictureUri = builder.build();

                                try {
                                    sendLogin(uid, name, email, pictureUri.toString(), "fb");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                facebookLogout();

                            }
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id, name, email");
                    request.setParameters(parameters);
            request.executeAsync();
        }

        @Override
        public void onCancel() {
        }

        @Override
        public void onError(FacebookException e) {
            Toast.makeText(getApplication(), "Something went wrong, please try again later", Toast.LENGTH_LONG).show();
        }
    };

    public void facebookLogout() {
        LoginManager.getInstance().logOut();
    }