如何通过以下方法获取Facebook用户ID以及电子邮件名称

时间:2012-09-23 18:16:23

标签: android facebook-graph-api

如何获取facebook用户ID以及电子邮件,在以下getProfileInformation()中输入名称,这里我想获取用户ID,并希望在run()中显示toast消息以及电子邮件和名称;

public void getProfileInformation() {
    mAsyncRunner.request("me", new RequestListener() {
        @Override
        public void onComplete(String response, Object state) {
            Log.d("Profile", response);
            String json = response;
            try {
                JSONObject profile = new JSONObject(json);
                // getting name of the user
                final String name = profile.getString("name");
                // getting email of the user
                final String email = profile.getString("email"); 
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() { 
                        Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email , Toast.LENGTH_LONG).show();
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onIOException(IOException e, Object state) {
        }

        @Override
        public void onFileNotFoundException(FileNotFoundException e,
                Object state) {
        }

        @Override
        public void onMalformedURLException(MalformedURLException e,
                Object state) {
        }

        @Override
        public void onFacebookError(FacebookError e, Object state) {
        }
    });
}

1 个答案:

答案 0 :(得分:3)

您可以在请求中传递捆绑包中的必填字段:

public void getProfileInformation() {
    Bundle params = new Bundle();
    params.putString("fields", "id,name,email");

    mAsyncRunner.request("me", params, new RequestListener() {
    @Override
    public void onComplete(String response, Object state) {
        Log.d("Profile", response);
        String json = response;
        try {
            JSONObject profile = new JSONObject(json);
            // getting name of the user
            final String name = profile.getString("name");
            // getting email of the user
            final String email = profile.getString("email"); 
            final Long id = profile.getLong("id");
            runOnUiThread(new Runnable() {
                @Override
                public void run() { 
                    Toast.makeText(getApplicationContext(), "ID:" + id + "\nName: " + name + "\nEmail: " + email , Toast.LENGTH_LONG).show();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
...

请注意,您需要“电子邮件”权限。